NoteOfMySQL 05 約束控制

2022-07-17 14:00:31 字數 3039 閱讀 6637

在mysql中,各種完整性約束是作為資料庫關係模式定義的一部分。一旦定義了完整性約束,mysql伺服器會隨時檢測處於更新狀態的資料庫內容是否符合相關的完整性約束,從而保證資料的一致性與正確性。如此,既能有效地防止對資料庫的意外破壞,又能提高完整性檢測的效率,還能減輕資料庫程式設計人員的工作負擔。

constraint 完整性約束條件名 [primary key | foreign key | check] 短語
用於保證資料庫表中記錄的唯一性。

(1)設定單字段id【列級完整性語法】

-- 定義表屬性後

primary key (col_name)

-- 定義表屬性時

col_name type [other options] primary key

(2)設定多欄位id【列級完整性語法】
-- 定義表屬性後

primary key (col_name1, col_name2 ...)

(3)例子

(1)語法格式

-- 定義表時

col_name type [other options] references super_table(super_state)

-- 定義表後

foreign key [foreign_name] (state) references super_table(super_state)

-- 建立表後

alter table table_name add [constraint foreign_name] foreign key (state) references super_table(super_state)

[ on delete ] 

[ on update ]

(2)引數說明

引數說明

foreign_name

外鍵名cascade

刪除或修改父表記錄時,會自動刪除或修改子表對應的記錄

restrict

與no action功能一致,為預設值

set null

刪除或修改父表記錄時,會將子表中對應的外鍵值設定為null

no action

刪除或修改父表記錄時,若子表中存在與之對應的記錄,則操作失敗

(4)例子

-- 定義表時:直接在資料型別後新增"not null"

create table table_name (

col_name type [other_options] not null;

);-- 建立表後

alter table table_name modify col_name type not null;

非空約束限制該字段的內容不能為空,但可以是空白。

-- 定義表時:直接在資料型別後新增"unique"

create table table_name (

col_name type [other_options] unique;

);-- 建立表後

alter table table_name modify col_name type [other_options] unique;

4.4 例子

-- 定義表時

create table table_name (

col_name type [other_options] default 預設值;

-- 定義表時

create table table_name (

col_name type [other_options] auto_increment;

);

檢查約束可以檢查資料表字段的有效性,如數值的限制。

前面的預設值約束和非空約束可看作是特殊的檢查約束。

alter table table_name drop [ primary key | foreign key 外鍵名];
引數說明:外鍵名可以通過顯示**詳情檢視(show create table table_name)。

注:刪除外來鍵約束後,在desc之後會發現在key一列還會留下mul的字樣,這個其實就是索引的意思。可以通過alter table table_name drop index 列名;來進行刪除,也可以通過alter table table_name add index(列名);進行新增。

NoteOfMySQL 10 觸發器與事件

觸發器是由事件來觸發某個操作,這些事件包括insert語句 update語句 delete語句,當資料庫系統執行這些事件時,就會啟用觸發器執行相應的操作。事件排程器 event schedule 用作定時執行某些特定任務來取代原先只能由作業系統的計畫任務來執行的工作。create trigger t...

字元0 數字0和 0

binoct dechex 縮寫 字元 解釋0000 000000 00nut null 空字元00110000 6048300 字元0ascii碼值 0 表示空字元,空字元就是平時所說的 0 字元 0 ascii碼值為 48,如 012 字串中的 0 表示字元 0 數字 0,所說的數字 0,就是平...

C語言 0 和0和 0

共同點 都是字元 不同點 0 對應的ascii碼是0,是ascii碼表中的第乙個字元,即空字元 判斷乙個字串是否結束的標誌就是看是否遇到 0 0 對應的ascii碼是48,48對應的十六進製制數就是0x30。0 是字串常量,字串常量是由一對雙引號括起的字串行。字串常量可以含乙個或多個字元。0 是字元...