文章目錄
一、表的約束
1、約束類型
非空約束
不能爲空值NULL
not null
主鍵約束
唯一非空,能唯一標識一行記錄,一個表只能有一個主鍵
primary key
唯一約束
唯一,並且可以爲空值NULL
,並且空值NULL
可以不唯一
unique
外鍵約束
主表 → 引用列
外鍵表 → 外鍵列
被引用的列必須是主鍵(primary key
)或者唯一鍵(unique
)
外鍵表的外鍵列 引用 主表的引用列
foreign key
檢查約束
在MySQL中,check
關鍵字是不起作用的。
如果想要限制某一列的取值範圍,應該使用觸發器來實現。
默認值約束
設置默認值
Tips:有些分類中也不把默認值當成約束
default
2、添加約束
添加約束的時機
- 創建表的時候
- 修改表的時候
添加約束的分類
- 列級別:所有約束都可以在列級別(MySQL中,外鍵約束寫在列級別是不起作用的)
- 表級別:除了非空約束、默認值約束以外,其他約束都支持寫在表級別
二、表的CRUD操作(DDL語句)
1、C(Create):創建
總體格式
create table if not exists 表名(
列名1 數據類型1 [default 值1] [列級別約束],
列名2 數據類型1 [default 值2] [列級別約束],
......
列名n 數據類型n [default 值n] [列級別約束],
[表級別約束],
[表級別約束],
......
[表級別約束]
) engine=INNODB default charset=utf8;
創建舉例(創建學生表)
create table if not exists student(
sno int primary key,
sname varchar(20) not null,
gender enum('男', '女') default '男',
interest set('游泳', '打球', '跑步'),
age int default 18
);
create table if not exists student(
sno int,
sname varchar(20) not null,
gender enum('男', '女') default '男',
interest set('游泳', '打球', '跑步'),
age int default 18,
constraint stu_sno_pk primary key(sno)
);
2、R(Retrieve):查詢
查詢當前數據庫下所有表的信息
show tables;
查詢創建表的結構、信息(字符集等)
show create table 表名;
desc 表名;
Tips:具體的查詢數據的操作放到以後講
3、U(Update):更新
修改表的名字
alter table 表名 rename to 新表名;
rename table 表名 to 新表名;
修改表的字符集
alter table 表名 character set 字符集名稱;
給表添加一列
alter table 表名 add 列名 數據類型;
修改表中某一列的名字、數據類型
alter table 表名 change [column] 列名 新列名 新數據類型;
alter table 表名 modify [column] 列名 新數據類型;
刪除表中某一列
alter table 表名 drop [column] 列名;
給表添加一個約束
- 添加非空約束
alter table 表名 modify [column] 列名 列類型 not null;
- 添加默認值
alter table 表名 modify [column] 列名 列類型 default 默認值;
- 添加主鍵約束(列級別)
alter table 表名 modify [column] 列名 列類型 primary key;
- 添加主鍵約束(表級別)
alter table 表名 add [constraint 約束名] primary key(列名);
- 添加唯一約束(列級別)
alter table 表名 modify [column] 列名 列類型 unique;
- 添加唯一約束(表級別)
alter table 表名 add [constraint 約束名] unique(列名);
- 添加外鍵約束
alter table 表名 add [constraint 約束名] foreign key(外鍵列) references 主表名(引用列);
刪除表中一個約束
-
刪除非空約束
alter table 表名 modify [column] 列名 列類型 [null];
(Tips:要注意之前有沒有默認值之類的,否則直接寫上面的語句會把默認值也一併刪除)
-
刪除默認值
alter table 表名 modify [column] 列名 列類型;
(Tips:要注意之前有沒有非空約束之類的,否則直接寫上面的語句會把默認值也一併刪除)
-
刪除主鍵約束 (上面的兩種方式是刪不掉主鍵的)
alter table 表名 drop primary key;
-
刪除唯一約束
alter table 表名 drop index(列名) 約束名;
(Tips:如果沒有具體約束名是無法刪除的)
-
刪除外鍵約束
alter table 表名 drop foreign key(列名) 約束名;
(Tips:如果沒有具體約束名是無法刪除的)
4、D(Delete):刪除
刪除表
drop table 表名;
drop table 表名 if exists 表名;
三、小練習
假設現在有員工表(emp),需要作出以下修改
- 在【員工表】中添加【性別】一列,列名爲
gender
、類型爲char(2)
、默認值爲'男'
alter table emp add column gender char(2) default '男';
- 修改【員工表】中【性別】一列,使其數據類型爲
char(4)
alter table emp modify column gender char(4) default '男';
- 修改【員工表】中【性別】一列,使其默認值爲
'女'
alter table emp modify column gender char(4) default '女';
- 刪除【員工表】中【性別】一列
alter table emp drop column gender;