使用WHERE子句计算MySQL中多个联接表的DISTINCT行

时间:2019-01-10 18:15:29

标签: mysql sql mysqli

我有三个表:业务,检查和违规。我有以下查询:

SELECT b.id, b.name, b.address, b.city, b.state, b.type, i.date
FROM businesses AS b
RIGHT JOIN inspections i ON i.business_id = b.id
RIGHT JOIN (SELECT inspection_id FROM violations) AS v ON v.inspection_id = i.id
WHERE b.type = 'hospital' AND i.date BETWEEN "2019-01-01" AND "2019-01-03";

我想找出结果中返回的明显违规次数(简单,这是行数),检查和业务。我尝试使用COUNTGROUP BY,但无法使其正常工作。

我需要的是类似的东西

table      | count
------------------
businesses | 10
inspections| 23
violations | 100

任何指针将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以这样操作,它将所有计数放在一行中:

SELECT COUNT(DISTINCT b.id) AS businesses, 
       COUNT(DISTINCT i.id) AS inspections,
       COUNT(DISTINCT v.id) AS violations
FROM businesses AS b
INNER JOIN inspections AS i ON b.id = i.business_id AND i.date BETWEEN "2019-01-01" AND "2019-01-03"
LEFT JOIN violations AS v ON i.id = v.inspection_id
WHERE b.type = 'hospital'

使用INNER JOIN仅返回在该日期范围内已检查的企业数。如果要统计所有业务,请使用OUTER JOIN