从两个连接表中获取计数

时间:2015-03-10 01:32:28

标签: sql sqlite join count

我有4个表,每个表都有一对多的关系:

client -< inspection -< car -< issue

我试图选择客户的名称和地址以及检查次数和问题数量。

以下是我目前的情况:http://sqlfiddle.com/#!5/e62ba/29/0

在上面的示例中,client._id = 1的结果应为:

 client_name    client_address   Inspection count   Issue count
 "John"         "1 Main street"  2                  3

client._id = 2应该是:

 client_name    client_address   Inspection count   Issue count
 "Jane"         "1 Wall street"  0                  0

是否可以在一个查询中实现此结果,或者我是否必须使用子查询来解决问题?

1 个答案:

答案 0 :(得分:1)

您可以使用count(distinct)

执行此操作
SELECT c.client_name, c.client_address,
       COUNT(DISTINCT i._id) AS "Inspection count",
       COUNT(DISTINCT iss._id) AS "Issue count"
FROM client c LEFT JOIN
     inspection i
     ON c._id = i.client_id LEFT JOIN
     (car ca INNER JOIN
      issue iss
      ON iss.car_id = ca._id
     )
     ON ca.inspection_id = i._id
WHERE c._id = 1;