日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

SQL连接多表

發(fā)布時(shí)間:2023/12/31 数据库 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SQL连接多表 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

SQL連接多表

  • 內(nèi)連接
    • 使用 where 完成多表的連接
    • 使用 cross join 得到 兩個(gè)表的笛卡爾乘積
    • 使用 內(nèi)連接 xxx inner join xxx on 條件
    • 連接兩個(gè)以上的表
  • 外連接
  • 自連接
    • 匯總函數(shù) + 多表連接

內(nèi)連接

因?yàn)橐诓煌谋碇胁樵償?shù)據(jù)。在查詢的過(guò)程中需要指定按照哪個(gè)維度來(lái)進(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í)也可以指定表的名稱 ,舉例:

select product_type,sale_price from product p, shopproduct s wherep.product_id = s.product_id;

注意: 如果不指定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 直接完成連接

select product_type,sale_price from product join shopproducton product.product_id = shopproduct.product_id;

連接兩個(gè)以上的表

舉例:查詢某個(gè)客戶購(gòu)買了哪些商品 ?

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
select distinct c.cust_id from customer c left outer join orders o on c.cust_id = o.cust_id whereo.cust_id is null ;

自連接

場(chǎng)景:某個(gè)供應(yīng)商在不同國(guó)家中使用的名稱

方法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è)顧客訂購(gòu)的商品總金額

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é)

以上是生活随笔為你收集整理的SQL连接多表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。