欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MySQL中檢查約束舉例詳細(xì)講解

 更新時(shí)間:2025年03月28日 08:28:47   作者:藝杯羹  
MySQL 檢查約束(CHECK)是用來(lái)檢查數(shù)據(jù)表中字段值有效性的一種手段,下面這篇文章主要介紹了MySQL中檢查約束的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下

一. 簡(jiǎn)介

檢察約束屬于DDL

約束可以理解成一種校驗(yàn)方式

 一共有5種約束,現(xiàn)在分別講解一下

  • 主鍵約束(Primary Key)

    不允許為空

    不允許有重復(fù)值出現(xiàn)

    保證數(shù)據(jù)的唯一性

  • 外鍵約束(Foreign Key)

    允許有空值

    允許有重復(fù)

    值必須是參照表的參照列中所包含的值

    保證數(shù)據(jù)的參照完整性

  • 唯一性約束(Unique)

    相同值只能出現(xiàn)一次

    允許為多個(gè)列添加唯一性約束

    保證數(shù)據(jù)的唯一性

  • 非空約束(Not Null)

    列中不能有空值

    允許重復(fù)值

    允許為多個(gè)列添加非空約束

    保證數(shù)據(jù)沒(méi)有空值

  • 檢查約束(Check)

    用戶自己定義約束條件

    保證數(shù)據(jù)滿足自定義的條件約束

    MySQL 目前不支持檢查約束

二. 主鍵約束(primary key

1. 添加主鍵約束

alter table 表名 add primary key(列名)

顯然這里的id字段(列)要設(shè)置成主鍵

alter table students add primary key(id);

因?yàn)槭侵麈I,那么在當(dāng)前表中是唯一的

如果主鍵是 int 型,那么就可以使用自動(dòng)增長(zhǎng)

alter table 表名 modify 主鍵 類型 auto_increment

alter table student modify id int auto_increment

2. 刪除主鍵

alter table 表名 drop primary key

alter table students drop primary key;

三. 外鍵約束(Foreign Key)

1. 添加外鍵

alter table 表名 add constraint 約束名 foreign key(列名) references 參照的表名(參照的列名)單詞:

constraint : 約束

references:引用

alter table students
add constraint fk_students_courses
foreign key (course_id)
references courses(id);  

2. 刪除外鍵

alter table 表名 drop foreign key 約束名

alter table students
drop foreign key fk_students_courses;    

四. 唯一性約束(Unique)

1. 添加唯一約束

alter table 表名 add constraint 約束名 unique(列名)

alter table students
add constraint uk_students_name
unique (name);  

2. 刪除唯一約束

alter table 表名 drop key 約束名

alter table students
drop key uk_students_name;    

五. 非空約束(Not Null)

1. 添加非空約束

alter table 表名 modify 列名 類型 not null單詞:

modify:修改

在修改的時(shí)候添加非空約束

alter table students
modify name varchar(50) not null;   

2. 刪除非空約束

alter table modify 列名 類型 null

alter table students
modify name varchar(50) null;  

六. 創(chuàng)建表時(shí)添加約束

直接可以在創(chuàng)建的時(shí)候順便添加約束

create table enhanced_students (
    -- 添加主鍵約束,并自動(dòng)增長(zhǎng)
    id int auto_increment primary key,
    -- 添加非空約束(不能為空)
    name varchar(50) not null,
    gender enum('男', '女') not null,
    -- 添加唯一約束
    students_name varchar(30) unique
);    

七. 總結(jié)

到此這篇關(guān)于MySQL中檢查約束的文章就介紹到這了,更多相關(guān)MySQL檢查約束內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論