sql基礎(2)之資料庫的約束

2021-09-26 10:19:34 字數 2755 閱讀 9605

唯一約束(unique):

非空約束(not null):

自增長約束 (auto_increment):

非負約束 (unsigned):

列舉約束

刪除主鍵約束

外來鍵約束(foreign key)

級聯刪除(on delete cascade):

級聯更新(on update cascade):

概念:對插入表中的資料做出的一定的限定

特點:非空且唯一,一張表只能存在乙個主鍵

1.新增主鍵約束的方法:

create table 表名 (列1 資料屬性 primary key,…)

alter table 表名 add primary key (列名)

create table 表名 (列1 資料屬性 …)

primary key(列1)

2.設定聯合主鍵

將多個字段看做乙個整體設定為主鍵

設定聯合主鍵的方法:

create table 表名 (列1 資料屬性 …)

primary key(列1,列2)

alter table 表名 add primary key (列1,列2)

特點:資料唯一,對於null值不起作用

語法結構:

create table 表名 (列1 資料屬性 unique …)

特點:表中的資料不為null值

語法結構:

create table 表名 (列1 資料屬性 not null …)

非空約束和唯一約束的結合與主鍵的區別:

可以給多個列設定非空且唯一

create table 表名(

列2 資料屬性 not null unique,

列1 資料屬性not null unique

特點:配合主鍵約束來使用,並且主鍵欄位的型別 是個整數型字段

create table 表名(

列1 資料屬性primary key auto_increment

列1的資料會從1不斷累計,但是如果移除掉最後的一行資料,資料會從刪除的

地方往後執行,不會再繼續

– tinyint -128–127

create table test11(

id tinyint,

)insert into test11 values(127);

create table test12(

id tinyint unsigned, – 非負約束

)insert into test12 values(255);

create table test13(

列1 enum(『選項1』,『選項2』,『選項3』) – enum 列舉型別

)

刪除主鍵約束:分兩種情況

情況2: 這個字段,是乙個int型別字段,既有主鍵約束,又有自增長約束,那麼得先刪除自增長約束,在刪除主鍵約束

設定外來鍵約束的原因:

為了保證資料的有效性和完整性,我們需要在多表的一方新增外來鍵約束,特點如下:

在多(主)表的一方不能增加單(從)表沒有的資料

在單(從)表的一方不能刪除多(主)表一方存在的資料

create table user(

id int primary key auto_increment,

username varchar(20)

);create table orders(

id int primary key auto_increment,

totalprice double,

user_id int

);alter table orders add foreign key(user_id) references user(id);

在外鍵的約束的情況下,先刪除使用者的所有訂單,然後刪除使用者

一般在上線的時候新增,在測試時一般不會新增級聯刪除。

alter table orders add foreign key(user_id) references users(id) on delete cascade;

當在多表中修改資料可以在單錶也是會修改的

create table zhu(

zid int primary key auto_increment,

zname varchar(20)

create table cong(

zid int primary key auto_increment,

zscore int,

zzid int,

– 方式2:建表的時候就加上了級聯更新和級聯刪除

foreign key(zzid) references zhu(zid) on delete cascade on update cascade

);

關於sql資料庫的約束

約束條件在資料庫中的使用。check 約束用於限制列中的值的範圍。如果對單個列定義 check 約束,那麼該列只允許特定的值。如果對乙個表定義 check 約束,那麼此約束會在特定的列中對值進行限制。建立約束 如以下例子 建立如下兩個表 create table kkk tel char 13 pr...

sql資料庫中的約束

先用設計器建立約束,再用 建立約束。資料庫約束是為了保證資料的完整性 正確性 而實現的一套機制 1.非空約束 選擇核取方塊 2.主鍵約束 唯一且不為空,選中列,右鍵設為主鍵 3.唯一約束 唯一允許為空,但只能出現一次,右鍵,索引 鍵,新增,型別 唯一,選擇列 表示唯一約束列不能有重複的值 表中可以包...

SQL基礎之資料庫快照

1.認識快照 如名字一樣,資料庫快照就可以理解為資料庫某一時刻的 它記錄了此時資料庫的資料資訊。如果要認識快照的本質,那就要了解快照的工作原理。當我們執行t sql建立快照後,此時就會建立乙個或多個稀疏檔案。稀疏檔案的個數與資料庫資料檔案的個數相等且一定要相等,否則會報錯。此時,稀疏檔案只是乙個空檔...