简体   繁体   English

SQL Query连接多个表

[英]SQL Query to join multiple tables

I have 4 tables that I need to connect in order to get the reports that I need. 我有4个表需要连接才能获得我需要的报告。 But I'm confused on how to write the query. 但我对如何编写查询感到困惑。 Below are the sample of the tables: 以下是表格的示例:

Client Table 客户表

client_id  |  client_name  |  con_id
----------:|:-------------:|:-------
    1      |     ABC       |  1
    2      |     DEF       |  1
    3      |     GHI       |  2

Consultant 顾问

con_id  |  con_name
-------:|:---------
   1    |    Ani
   2    |   Robby

Perm 彼尔姆

pid  |  client_id  |  date
----:|:-----------:|:-----------
 1   |      1      |  2014-08-09
 2   |      1      |  2014-03-02
 3   |      2      |  2014-03-02 

Temp 温度

tid  |  client_id  |  date
----:|:-----------:|:-----------
 1   |     2       |  2013-02-09
 2   |     3       |  2011-03-02
 3   |     3       |  2012-04-02 

The end result of the report that I want to show is something like this: 我要展示的报告的最终结果是这样的:

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

I'm trying to use the LEFT OUTER JOIN , but I don't get the result that I want. 我正在尝试使用LEFT OUTER JOIN ,但我没有得到我想要的结果。 Can anyone help me to figure out the query? 任何人都可以帮我弄清楚查询吗? thanks in advanced. 提前致谢。

this is a simple outer join query with count and group by,just join your client table with the related ones and count only the distinct associations 这是一个带有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 that you want to select .... ....你要选择的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