sql多表關係

2021-10-09 17:42:44 字數 3147 閱讀 6356

(1)初始化資料

(2)一對多的建立流程

》建立主表(分類表)

》建立從表(商品表)

》給主表和從表之間新增外來鍵約束

alter table 從表 add [constraint] [外來鍵名稱] foreign key (從表外來鍵欄位名) references 主表 (主表的主鍵);
》給主表新增資料(隨便新增)

》給從表新增資料(新增資料是必須依賴主表)

(3)一對多特點

新增資料: 主表:隨意新增,從表:受主表限制

刪除資料: 主表:如果某一行的資料受到從表的依賴,則不能刪除, 從表:可以隨意刪除

練習一對多關係

use day13_2

》建立主表(分類表)

create table category(

cid int primary key auto_increment,

cname varchar(20)

)》建立從表(商品表)

create table product(

pid int primary key auto_increment,

pname varchar(20),

price double,

cid int -- 外來鍵 表示屬於哪個分類

)》給主表和從表之間新增外來鍵約束

`alter table 從表 add [constraint] [外來鍵名稱] foreign key (從表外來鍵欄位名) references 主表 (主表的主鍵);`

alter table product add foreign key (cid) references category(cid)

》給主表新增資料(隨便新增)

insert into category value(null,'電子')

insert into category value(null,'服裝')

》給從表新增資料(新增資料是必須依賴主表)

insert into product value(null,'聯想',2000,1)

insert into product value(null,'華為',4000,1)

insert into product value(null,'真維斯',100,2)

1建立訂單表(主表) order

create table orders(

oid int primary key auto_increment,

money double

)2建立中間表(從表) 儲存交叉線

create table orders_product(

oid int , -- 必須存在 外來鍵

pid int -- 必須存在 外來鍵

)3給中間表建立外來鍵約束(2次)

alter table orders_product add foreign key (oid ) references orders(oid);

alter table orders_product add foreign key (pid ) references product(pid);

4給訂單表新增資料(隨意)

insert into product value(null,'lv',30000,2)

5給中間表新增資料(受限)

練習多對多關係

演員表與角色表關係

》 建立演員表(左側主表)

create table users(

uid int primary key auto_increment,

uname varchar(20)

)》 建立角色表(右側主表)

create table role(

rid int primary key auto_increment,

rname varchar(20)

)》 建立中間表(從表)

create table users_role(

rid int , -- 資料必須在role存在

uid int -- 資料必須在users存在

)》建立外來鍵約束(2次)

alter table users_role add foreign key (rid) references role(rid);

alter table users_role add foreign key (uid) references users(uid);

練習-角色表和許可權表

》 建立許可權表

create table privilege(

pid int primary key auto_increment,

pname varchar(20)

)》 第二個中間表

create table privilege_role(

pid_fk int , -- 外來鍵

rid_fk int -- 外來鍵

)》建立外來鍵約束

alter table privilege_role add foreign key (pid_fk) references privilege(pid);

alter table privilege_role add foreign key (rid_fk) references role(rid);

》給許可權表新增資料

》給中間表新增資料

論SQL語句中的Left join 多表關係

以前,被子查詢這種語句弄得超迷糊,然後在交大的學習平台上發現原來很多情況都不需要子查詢,直接乙個where就搞定了,但是並不了解哪些對應關係。但是啊,不知道其他初學者有沒有這種感受 看網上哪些例子是非常懂的,然而自己用在專案中,思維卻卡機了。無奈之下,我還是繼續研究了哪位大神的原始碼,如下 sele...

SQL多表連線

oracle8 select a.b.from a,b where a.id b.id 相當於左聯接 select a.b.from a,b where a.id b.id 相當於右聯接 oracle9 支援以上的寫法,還增加了leftjoin right join等 select a.b.from...

sql 多表關聯

專案中遇到多表關聯查詢,device info與device oper是一對多關係,project info,branch info與device info是一對多關係。多表的查詢 select o.d.devicename,p.projectname,b.branchname r.releasei...