繁体   English   中英

SQL Query连接多个表

[英]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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM