03 mysql常用的約束條件及執行

2021-10-12 17:43:53 字數 2023 閱讀 7849

* 對錶中的資料進行限定,保證資料的正確性、有效性和完整性。

* 分類:

1. 主鍵約束: primary key

2. 非空約束: not null

3. 唯一約束: unique

4. 外來鍵約束: foreign key

* 非空約束:

1.建立時新增

create table student (

id int,

name varchar(32) not null

);2.建立表完後,修改

alter table student modify name varchar(32) not null;

3.刪除非空約束

alter table student modify name varchar(32);

* 唯一約束:值不能重複,但是null可以出現多個

1.建立時新增

2.修改

alter table student modify phone_number varchar(20) unique;

3.刪除唯一約束

alter table student drop index phone_number;

* 主鍵約束:非空且唯一,一張表只能有乙個主鍵。表中記錄的唯一標識。

1.建立時新增主鍵

create table student (

id int primary key, 給id新增主鍵

name varchar(32) not null

);2.修改

alter table student modify id int primary key;

3.刪除主鍵

alter table student drop primary key;

4.自動增長:如果某一列是數值型別的,使用auto_increment可以完成值的自動增長。

create table student (

id int primary key auto_increment, 給id新增主鍵

name varchar(32) not null

);* 外來鍵約束

1.建立時新增外來鍵

create table student (

id int primary key, 給id新增主鍵

name varchar(32) not null

外來鍵列constraint 外來鍵名稱 foreign key (外來鍵列名稱) references 主表名稱(主表列名稱)

);create table employee(id int primary key auto_increment,name varchar(20),age int,dep_id int,constraint emp_dept foreign key(dep_id) references employee(id));

2.刪除外來鍵

alter table employee drop foreign key emp_dept;

3.新增外來鍵(引用時最好引用主鍵或者唯一值)

不然會出現:1215 - cannot add foreign key constraint

alter table employee add constraint emp_dept foreign key(dep_id) references department(id)

4.級聯:

如果設定時有問題,檢查所設定的鍵的值是否匹配

設定級聯更新

alter table employee add constraint emp_dept foreign key(dep_id) references department(id) on update cascade;

設定級聯刪除

alter table employee add constraint emp_dept foreign key(dep_id) references department(id) on update cascade on delete cascade;

MySQL 約束條件

1 非空約束 not null規定某個欄位在插入的時候不能有null,標誌位非空的時候插入的時候必須給值,不然會報錯 2 唯一約束 unique規定某個字段在整個這一列中是唯一 3 主鍵 非空且唯一是主要特徵。主鍵可以唯一標識一行資料 可以從多行資料中定位到該資料 但是唯一標識一行資料的字段 或字段...

mySQL之約束條件

primary key pk 標識該字段為該錶的主鍵,可以唯一的標識記錄 foreign key fk 標識該字段為該錶的外來鍵 not null 標識該欄位不能為空 unique key uk 標識該字段的值是唯一的 auto increment 標識該字段的值自動增長 整數型別,而且為主鍵 de...

列舉mysql的約束條件 MySql約束條件彙總

約束條件約束條件是在表上強制執行的資料檢驗規則 用來保證建立的表的資料完整性和準確性 主要在兩方面對資料進行約束 空值和重複值 主鍵約束 primary key 每個表只能由乙個主鍵 主鍵值須非空不重複 可設定單字段主鍵,也可設定多欄位聯合主鍵 聯合主鍵中多個欄位的取值完全相同時,才違反主鍵約束 新...