柚子快報(bào)邀請碼778899分享:數(shù)據(jù)庫約束命令
柚子快報(bào)邀請碼778899分享:數(shù)據(jù)庫約束命令
mysql中:
id中存在auto_increment
CREATE TABLE u_user(
id int PRIMARY KEY auto_increment,
u_name VARCHAR(10) NOT NULL UNIQUE,
age int CHECK(age>0 && age<=120),
u_status char(1) DEFAULT(1),
gender char(1)
);
INSERT into u_user(u_name,age,u_status,gender)VALUES("李明",20,"1","男"),("王麗",18,"1","女");
外鍵約束:
-- 創(chuàng)建主表(班級表)
create table class(
c_id int(4) primary key auto_increment,
c_name varchar(10)
);
-- 班級表添加數(shù)據(jù)
insert into class values(NULL, 'xg1901'), (NULL, 'xg1902');
-- 創(chuàng)建從表(學(xué)生表)
create table stu_table(
s_id int PRIMARY key auto_increment,
s_name varchar(10) not null,
s_sex char(1) check(s_sex = '男' or s_sex = '女'),
s_age int(3) check(s_age > 0 and s_age < 100),
c_id int(4),
-- 創(chuàng)建時(shí)添加表級外鍵約束
constraint fk_c_id foreign key (c_id) references class(c_id)
);
-- 創(chuàng)建從表(學(xué)生表)
create table stu_table(
s_id int PRIMARY key auto_increment,
s_name varchar(10) not null,
s_sex char(1) check(s_sex = '男' or s_sex = '女'),
s_age int(3) check(s_age > 0 and s_age < 100),
c_id int(4)
#創(chuàng)建時(shí)添加外鍵
CONSTRAINT fk_c_id FOREIGN KEY(c_id) REFERENCES class(c_id)
);
-- 學(xué)生表中插入數(shù)據(jù)
insert into stu_table values (NULL, '香菱', '女', 18, 1);
insert into stu_table values (NULL, '行秋', '男', 18, 2);
insert into stu_table values (NULL, '胡桃', '女', 16, 2);
insert into stu_table values (NULL, '班尼特', '男', 18, 1);
不能刪除外鍵:
刪除外鍵語句:
ALTER TABLE stu_table drop foreign key fk_c_id;
刪除或更新外鍵(級聯(lián)操作)
使用cascade,當(dāng)父表刪除或更新對象記錄時(shí),首先檢查該記錄是否有對應(yīng)外鍵,若有,則也刪除或更新外鍵在子表中的記錄。
set null:當(dāng)父表刪除或更新對象記錄時(shí),首先檢查該記錄是否有對應(yīng)外鍵,若有,則設(shè)置子表中該外鍵的值為null。
父表/主表:含有被依賴的字段的表。
子表/從表:使用外鍵約束的表。
原始表:
使用語句:
#刪除或更新外鍵
ALTER TABLE stu_table ADD CONSTRAINT fk_c_id FOREIGN KEY(c_id) REFERENCES class(c_id) ON UPDATE CASCADE ON DELETE CASCADE;
柚子快報(bào)邀請碼778899分享:數(shù)據(jù)庫約束命令
好文閱讀
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。