標籤:分享 pre 主鍵 標題 結構 資料 pad number 寬度
MYSQL中的表
表(TABLE) 是一種結構化的檔案,可用來儲存某種特定類型的資料。表中的一條記錄有對應的標題,標題 稱之為 表的欄位。
MYSQL中表的各種操作建立
| 12345 |
CREATE TABLE 表名(欄位名1 類型[(寬度) 約束條件],欄位名2 類型[(寬度) 約束條件],欄位名3 類型[(寬度) 約束條件])ENGINE=innodb DEFAULT CHARSET utf8; |
create table student( id int not null auto_increment primary key, name varchar(250) not null, age int not null, sex enum(‘男‘,‘女‘) not null default ‘男‘, salary double(10,2) not null)engine=innodb default charset=utf8;ps: not null :表示此列不可為空 auto_increment :表示自增長,預設每次增長+1注意:自增長只能添加在主鍵或者唯一索引欄位上 primary key :表示主鍵(唯一且不為空白)engine =innodb :表示指定當前表的儲存引擎default charset utf8 :設定表的預設編碼集
建立表
主鍵,一種特殊的唯一索引,不允許有空值,如果主鍵使用單個列,則它的值必須唯一,如果是多列,則其組合必須唯一。 create table tb1( nid int not null auto_increment primary key, num int null ) 或 create table tb1( nid int not null, num int not null, primary key(nid,num) )
主鍵
自增,如果為某列設定自增列,插入資料時無需設定此列,預設將自增(表中只能有一個自增列) create table tb1( nid int not null auto_increment primary key, num int null ) 或 create table tb1( nid int not null auto_increment, num int null, index(nid) )注意:1、對於自增列,必須是索引(含主鍵)。 2、對於自增可以設定步長和起始值 show session variables like ‘auto_inc%‘; set session auto_increment_increment=2; set session auto_increment_offset=10; show global variables like ‘auto_inc%‘; set global auto_increment_increment=2; set global auto_increment_offset=10;
自增查詢表中的資料
| 1234567891011 |
#查詢表資料select 欄位(多個以","間隔) from 表名;例: select name,sex from student;或者: select * from student;#實際工作中不建議使用* #查看錶結構desc 表名;例: desc student; #查看建立表資訊show create table student; |
刪除表
| 12345 |
#刪除表drop table 表名; #清空表truncate table 表名; |
修改表
| 1234567891011121314151617 |
#添加表欄位alter table 表名 add 欄位名 類型 約束;例如: alter table student add age int not null default 0 after name;ps: after name 表示在name欄位後添加欄位 age. #修改表欄位方式一: alter table student modify 欄位 varchar(100) null;方式二: alter table student change 舊欄位 新欄位 int not null default 0;ps:二者區別:change 可以改變欄位名字和屬性modify只能改變欄位的屬性 #刪除表欄位 :alter table student drop 欄位名; #更新表名稱:rename table 舊錶名 to 新表名; |
#添加主鍵 : alter table student add primary key(欄位,"多個","間隔"); #移除主鍵 : alter table student drop primary key;ps:如果主鍵為自增長,以上方式則不被允許執行,請先去掉主鍵自增長屬性,然後再移除主鍵alter table student modify id int not null,drop primary key
更新主鍵操作
#添加外鍵: alter table 從表 add CONSTRAINT fk_test foreign key 從表(欄位) REFERENCES 主表(欄位);#移除外鍵: alter table 表 drop foreign key 外鍵名稱;ps:如果外鍵設定後想修改,那麼只能是先刪除,再添加
外鍵更新操作
#修改預設值 : alter table 表 alter 欄位 set default 100;#刪除預設值 :alter table 表 alter 欄位 drop default;
預設值更新操作 複製表
| 1234567 |
#只複製表結構和表中資料CREATE TABLE tb2 SELECT * FROM tb1;ps:主鍵自增/索引/觸發器/外鍵 不會 被複製 #只複製表結構create table tb2 like tb1;ps: 資料/觸發器/外鍵 不會被複製 |
MYSQL之表操作