[英]SQL Query to join multiple tables
我有4個表需要連接才能獲得我需要的報告。 但我對如何編寫查詢感到困惑。 以下是表格的示例:
客戶表
client_id | client_name | con_id
----------:|:-------------:|:-------
1 | ABC | 1
2 | DEF | 1
3 | GHI | 2
顧問
con_id | con_name
-------:|:---------
1 | Ani
2 | Robby
彼爾姆
pid | client_id | date
----:|:-----------:|:-----------
1 | 1 | 2014-08-09
2 | 1 | 2014-03-02
3 | 2 | 2014-03-02
溫度
tid | client_id | date
----:|:-----------:|:-----------
1 | 2 | 2013-02-09
2 | 3 | 2011-03-02
3 | 3 | 2012-04-02
我要展示的報告的最終結果是這樣的:
client_id | client_name | perm(COUNT) | temp(COUNT) | con_name
----------:|:-------------:|:-------------:|:-------------:|:---------
1 | ABC | 2 | 0 | Ani
2 | DEF | 1 | 1 | Ani
3 | GHI | 0 | 2 | Robby
我正在嘗試使用LEFT OUTER JOIN
,但我沒有得到我想要的結果。 任何人都可以幫我弄清楚查詢嗎? 提前致謝。
這是一個帶有count和group by的簡單外連接查詢,只需將您的client
表與相關聯的表連接起來,並僅計算不同的關聯
select
c.client_id,
c.client_name,
count(distinct p.pid) perm_count,
count(distinct t.tid) temp_count,
cn.con_name
from client c
left join Consultant cn on(c.con_id = cn.con_id)
left join Perm p on(c.client_id = p.client_id)
left join `Temp` t on(c.client_id = t.client_id)
group by c.client_id
Fiddle Demo
你應該在一個sql中通過joinig all query連接所有表。參見鏈接http://www.w3resource.com/sql/joins/using-a-where-cluase-to-join-two-tables-related-by-一個單柱主鍵或- foriegn密鑰-pair.php
SELECT a.client_id as client_id, a.client_name as client_name,
a.con_id as client_con_id,
b.con_id as con_id,
b.con_name as con_name,
c.pid as perm_id,
c.client_id as perm_client_id
c.date as perm_date
d.tid as temp_id,
d.client_id as tem_client_id
....你要選擇的Anthing ....
from client_table a
Inner join Consultant_table b on a.client_con_id = b.con_id
Inner join perm_table c on a.client_id= c.perm_client_id
Inner join Temp_table d on....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.