加入状态为打开或关闭的三个表

时间:2018-07-31 06:54:27

标签: php join

我有三个表,希望通过它们之间的公共列进行内部联接。

客户

ClientID    Name
=========   ============
   2          Jaan    
   12         Sajesh
   13         Ruble

clients_of_cases:

ClientsOfCaseID   ClientID    CaseID  
============      ========    ========   
     157             2          2
     139            12          8
     141            12          7
     364            12          225
     11             13           9
     12             13          10
     13             13          11
    312             13          184

案件

CaseID       IsClosed  
==========   ========    
   2            1
   7            0
   8            1
   9            1
   10           1
   11           1
   184          1
   225          1

我需要以下内容:

  1. 我想向客户显示所有已结案的客户(Isclosed = 1)
  2. 获得任何案件未结(已关闭= 0)

我建立以下查询

1。

SELECT clients.ClientID,clients.Name,ccases.IsClosed 
FROM clients 
    JOIN clients_of_cases ON clients.ClientID=clients_of_cases.ClientID 
    JOIN ccases ON clients_of_cases.CaseID=ccases.CaseID 
WHERE ccases.IsClosed=1 
GROUP BY clients.ClientID

2。

SELECT clients.ClientID,clients.Name,ccases.IsClosed 
FROM clients 
JOIN clients_of_cases ON clients.ClientID=clients_of_cases.ClientID 
JOIN ccases ON clients_of_cases.CaseID=ccases.CaseID 
WHERE ccases.IsClosed=0 
GROUP BY clients.ClientID

但是它不会返回所需的结果...

我得到这个结果:

 ClientID  FirstName IsClosed
   ==============================
      12        Sajesh       0




 ClientID  FirstName IsClosed
    ==============================
      2         Jaan         1
      12        Sajesh       1
      13        Ruble        1

并希望得到以下结果:

 ClientID  FirstName IsClosed
   ==============================
      12        Sajesh       0

ClientID  FirstName IsClosed
==============================
  2         Jaan         1
  13        Ruble        1

2 个答案:

答案 0 :(得分:4)

要获得所有所有已结案的客户,我们可以尝试汇总:

SELECT c1.ClientID, c1. Name
FROM client c1
INNER JOIN clients_of_cases c2
    ON c1.ClientID = c2.ClientID
INNER JOIN ccases c3
    ON c2.CaseID = c3.CaseID
GROUP BY c1.ClientID, c1.Name
HAVING SUM(c3.IsClosed) = COUNT(*);

我们还可以使用一种非常相似的聚合方法来查找具有至少一个未结案件的客户:

SELECT c1.ClientID, c1. Name
FROM client c1
INNER JOIN clients_of_cases c2
    ON c1.ClientID = c2.ClientID
INNER JOIN ccases c3
    ON c2.CaseID = c3.CaseID
GROUP BY c1.ClientID, c1.Name
HAVING SUM(c3.IsClosed) < COUNT(*);   -- only difference from above is the HAVING clause

尽管您以当前的方式按客户进行汇总,但是我看到的主要缺陷是您试图使用WHERE子句来声明对案件的开/关状态的限制。相反,您需要将该逻辑放入HAVING子句中,然后在每个客户端组上进行断言。

答案 1 :(得分:2)

通过使用此查询将每个客户的未结案件数与案件总数进行比较,您可以在一个查询中获得两个结果:

SELECT c.ClientID, c.Name,
    CASE WHEN SUM(cc.IsClosed)=COUNT(cc.IsClosed) THEN 1 ELSE 0 END AS IsClosed
FROM client c
LEFT JOIN clients_of_cases coc ON coc.ClientID = c.ClientID
JOIN ccases cc ON cc.CaseID = coc.CaseID
GROUP BY c.ClientID
ORDER BY IsClosed

输出:

ClientID  Name     IsClosed
12        Sajesh   0 
2         Jaan     1 
13        Ruble    1 

请注意,此查询假定IsClosed仅是0或1。