Mysql中用SQL增長、刪除字段,修改字段名、字段類型、註釋,調整字段順序總結

在網站重構中,一般會進行數據結構的修改,因此添加,刪除,增長mysql表的字段是不免的,有時爲了方便,還會增長修改表或字段的註釋,把同字段屬性調整到一起。這些操做能夠在phpmyadmin或者別的mysql管理工具中完成,可是咱們有時爲了更方便的管理,會選擇寫sql語句來實現。
 
 

1.增長一個字段php

 代碼以下 複製代碼
//增長一個字段,默認爲空
alter table user add COLUMN new1 VARCHAR(20) DEFAULT NULL; 
//增長一個字段,默認不能爲空
alter table user add COLUMN new2 VARCHAR(20) NOT NULL;



2.批量怎加字段

方法一
這裏可使用事務html

 代碼以下 複製代碼

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 類型(長度));mysql

 代碼以下 複製代碼
alter table em_day_data add (f_day_house11 int(11),f_day_house12 int(11),f_day_house13 int(11));



 
3.刪除一個字段android

 代碼以下 複製代碼
//刪除一個字段
alter table user DROP COLUMN new2;


 
4.修改一個字段sql

 代碼以下 複製代碼
//修改一個字段的類型
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



例子:app

 代碼以下 複製代碼

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 字段名(跳到哪一個字段以後)
例子:網站

 代碼以下 複製代碼
alter table appstore_souapp_app_androidmarket;change getPriceCurrency getPriceCurrency varchar(50)   default null AFTER getPrice;
相關文章
相關標籤/搜索