表(TABLE) 是一種結構化的文件,可用來存儲某種特定類型的數據。表中的一條記錄有對應的標題,標題 稱之爲 表的字段。python
1
2
3
4
5
|
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;
1
2
3
4
5
6
7
8
9
10
11
|
#查詢表數據
select
字段(多個以
","
間隔)
from
表名;
例:
select
name
,sex
from
student;
或者:
select
*
from
student;
#查看錶結構
desc
表名;
例:
desc
student;
#查看建立表信息
show
create
table
student;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#添加表字段
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;
1
2
3
4
5
|
#刪除表
drop
table
表名;
#清空表
truncate
table
表名;
|
1
2
3
4
5
6
7
|
#只複製表結構和表中數據
CREATE
TABLE
tb2
SELECT
*
FROM
tb1;
ps:主鍵自增/索引/觸發器/外鍵 不會 被複制
#只複製表結構
create
table
tb2
like
tb1;
ps: 數據/觸發器/外鍵 不會被複制
|