SQL连接多表
SQL連接多表
- 內(nèi)連接
- 使用 where 完成多表的連接
- 使用 cross join 得到 兩個(gè)表的笛卡爾乘積
- 使用 內(nèi)連接 xxx inner join xxx on 條件
- 連接兩個(gè)以上的表
- 外連接
- 自連接
- 匯總函數(shù) + 多表連接
內(nèi)連接
因?yàn)橐诓煌谋碇胁樵償?shù)據(jù)。在查詢的過程中需要指定按照哪個(gè)維度來進(jìn)行查詢(即,按照哪個(gè)列,或者哪幾個(gè)列對(duì)數(shù)據(jù)進(jìn)行拼接和查詢)
使用 where 完成多表的連接
舉例1: 在商品表和銷售表中,找出兩者id相同的商品。== 找出商品表和銷售表中的商品類型和銷售價(jià)格
select product_type,sale_price from product, shopproduct whereproduct.product_id = shopproduct.product_id;運(yùn)行結(jié)果
同時(shí)也可以指定表的名稱 ,舉例:
注意: 如果不指定where的限制條件,那么就返回兩個(gè)表的笛卡爾乘機(jī)。
使用 cross join 得到 兩個(gè)表的笛卡爾乘積
select product_type,sale_price from product cross join shopproduct;使用 內(nèi)連接 xxx inner join xxx on 條件
select product_type,sale_price from product inner join shopproducton product.product_id = shopproduct.product_id;
注意, 也可以使用 join 直接完成連接
連接兩個(gè)以上的表
舉例:查詢某個(gè)客戶購買了哪些商品 ?
select p.product_name ## 商品名稱 from customers cjoin orders o on c.cust_id = o.cust_idjoin orderitems oi on oi.order_num = o.order_num join products p on p.product_id = oi.product_id where c.cust_name = 'The toy store'; ## 用戶名稱外連接
查詢沒有關(guān)聯(lián)到的記錄,可以使用外連接
- left outer join == left join
- right outer join == right join
舉例 :查詢沒有訂單的客戶id
自連接
場景:某個(gè)供應(yīng)商在不同國家中使用的名稱
方法1 :自連接(推薦使用)
selectdistinct v1.vend_name from vendors v1, vendors v2 where v1.vend_country = v2.vend_countryand v2.vend_name = '供應(yīng)商1名稱' ;方法2 :子查詢
selectdistinct vend_name from vendors where vend_country = (select distinct vend_countryfrom vendorswhere vend_name='供應(yīng)商1名稱') ;匯總函數(shù) + 多表連接
多個(gè)表中,每個(gè)顧客的訂單數(shù)
select c.cust_name, count(distinct o.order_name) from customers c join orders o on c.cust_id = o.cust_id group by c.cust_name ;查詢多個(gè)表中的,每個(gè)顧客訂購的商品總金額
select c.cust_name, sum(o.quantity) from customers c join orders o on c.cust_id = o.cust_idjoin orderitems oi on oi.order_num = o.order_num group by c.cust_name ;總結(jié)
- 上一篇: 熵权法确定权重
- 下一篇: Linux 抓包分析命令