SQL左外串連:明白左串連也就明白了右串連
兩表外串連
出貨表
客戶id、客戶名稱、產品id、產品數量、備忘
create table a_prod_out
(
custom_id int not null,
custom_name varchar(200) not null,
prod_id int default 0 null,
prod_num int default 0 null,
remark varchar(500) null,
constraint pk_a_prod_out primary key (custom_id)
)
產品表
產品id、產品名稱、生產廠家
create table b_prod
(
prod_id int not null,
prod_name varchar(200) not null,
manufacturer_id int default 0 null,
remark varchar(500) null,
constraint pk_b_prod primary key (prod_id)
)
左串連
左串連以左表為標準,並接右邊的部分資料,並接條件即產品id
此時左表資訊全部顯示,對應串連右邊中符合并接條件的資料
select a.custom_id,a.custom_name,b.prod_name,b.manufacturer_id
from a_prod_out a left outer join b_prod b
on a.prod_id = b.prod_id ;
三表外串連
廠商表 客戶對應用什麼產品
create table a_mfter
(
manufacturer_id int not null,
manufacturer_name varchar(200) not null,
constraint pk_a_mfter primary key (manufacturer_id)
)
select a.custom_id,a.custom_name,b.prod_name,c.manufacturer_name
from a_prod_out a
left outer join b_prod b
on a.prod_id = b.prod_id
left outer join a_mfter c
on b.manufacturer_id = c.manufacturer_id;
SQL結果同樣是以左表出貨表為標準,並接產品表和廠商表