yii 用于联接多个表的SQL查询

dojqjjoe  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(165)

我需要连接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,但是没有得到想要的结果。有人能帮我弄清楚这个查询吗?

vktxenjb

vktxenjb1#

这是一个带有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(第一次)

dly7yett

dly7yett3#

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....

相关问题