mysql中通過sql操作字段

2021-08-09 20:46:34 字數 2530 閱讀 1900

原文:

在**重構中,通常會進行資料結構的修改,所以新增,刪除,增加mysql表的字段是難免的,有時為了方便,還會增加修改表或字段的注釋,把同欄位屬性調整到一塊兒。這些操作可以在phpmyadmin或者別的mysql管理工具中完成,但是我們有時為了更方便的管理,會選擇寫sql語句來實現。

1.增加乙個字段

**如下

複製**

//增加乙個字段,預設為空

alter table user add column new1 varchar(20) default null; 

//增加乙個字段,預設不能為空

alter table user add column new2 varchar(20) not null;

2.批量怎加字段

方法一這裡可以使用事務

**如下

複製**

bagin;                                           //事務開始

alter table em_day_data add f_day_house7 int(11);

alter table em_day_data add f_day_house8 int(11);

alter table em_day_data add f_day_house9 int(11);

alter table em_day_data add f_day_house10 int(11);

commit;                                             //提交事務,事務結束

事務(transaction)是由一系列操作序列構成的程式執行單元,這些操作要麼都做,要麼都不做,是乙個不可分割的工作單位。

方法二 

mysql 批量為表新增多個字段

alter table 表名 add (欄位1 型別(長度),欄位2 型別(長度),欄位3 型別(長度));

**如下

複製**

alter table em_day_data add (f_day_house11 int(11),f_day_house12 int(11),f_day_house13 int(11));

3.刪除乙個字段

**如下

複製**

//刪除乙個字段

alter table user drop column new2;

4.修改乙個字段

**如下

複製**

//修改乙個欄位的型別

alter table user modify new1 varchar(10);

//修改乙個欄位的名稱,此時一定要重新指定該字段的型別

alter table user change new1 new4 int;

5.批量修改欄位名稱

**如下

複製**

alter table 表 change 修改前欄位名  修改後欄位名稱 int(11) not null,

change 修改前欄位名  修改後欄位名稱 int(11) not null,

change 修改前欄位名  修改後欄位名稱 int(11) not null,

change 修改前欄位名  修改後欄位名稱 int(11) not null,

change 修改前欄位名  修改後欄位名稱 int(11) not null

例子:**如下

複製**

alter table em_day_data change f_day_house11 f_day_hour11 int(11) not null,

change f_day_house12 f_day_hour12 int(11) not null,

change f_day_house13 f_day_hour13 int(11) not null,

change f_day_house14 f_day_hour14 int(11) not null,

change f_day_house15 f_day_hour15 int(11) not null,

change f_day_house16 f_day_hour16 int(11) not null,

change f_day_house17 f_day_hour17 int(11) not null

6,新增注釋

**如下

複製**

// 可以為表新增注釋

alter table `table_name` comment'注釋'; 

// 為字段新增注釋,同樣適用於修改

alter table `table_name` change `column_name` `column_name` type(longth) unsigned null default null comment '注釋'

7,調整字段順序:

alter table 表名

change 欄位名 新欄位名 字段型別 預設值 after 欄位名(跳到哪個字段之後)

例子:**如下

複製**

mysql 字段操作

1.新增字段 alter table 表名 add 列名 型別 約束 例 alter table students add birthday datetime 2.修改字段 1 修改欄位名 alter table 表名.table name rename column old column name...

Mysql 字段操作

alter table 表名 add 欄位1 型別 長度 欄位2 型別 長度 欄位3 型別 長度 alter table pro add add pro int 11 pro age int 11 pro lenth int 11 alter table pro add drop column ag...

通過sql批量更新字段內容

1.也許現在大家都不需要寫sql了,鑑於我技術比較落後,加上開發的系統還有在使用,所以還是有業務需要用到。2.伺服器搬家,導致資料庫裡,伺服器的路徑發生改變,所以要批量替換。設定網域名稱就不用管這個坑 檢索出要替換的內容條數 select count from shop item where pho...