我需要连接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
,但我没有得到我想要的结果。任何人都可以帮我弄清楚查询吗?谢谢你提前。
答案 0 :(得分:1)
这是一个简单的外部联接查询,包含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
答案 1 :(得分:0)
您应该通过在一个sql中加入所有查询来连接所有表。请参阅链接http://www.w3resource.com/sql/joins/using-a-where-cluase-to-join-two-tables-related-by-a-single-column-primary-key-or-foriegn-key-pair.php
答案 2 :(得分:-1)
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
....你想要选择的任何东西......
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....