如何从两个表中获取计数结果

时间:2019-01-18 11:51:20

标签: mysql sql join group-by count

我有两个表CarsDefect。我通过将car_id作为外键传递到缺陷表来保持关系。

我在汽车表中有3000条记录,在缺陷表中有16000条记录(具有open_defectclose_defect)。我试图找出所有具有未解决缺陷的Cars(3000)(如果没有针对car的未解决缺陷,则应返回0)。

我正在尝试一些查询:

SELECT cars.cars_id_primary ,IF(COUNT(defect.defect_id_primary)>0,1,0) AS `def_count`
FROM cars
LEFT JOIN defect ON cars.cars_id_primary = defect.cars_id AND defect.defect_status_id =1
WHERE cars.stage_id !=5 
GROUP BY cars.cars_id_primary
ORDER BY cars.updated_on

此查询给我结果,但是执行时间太长。 需要优化此查询。我坚持要优化。

欢迎任何帮助,谢谢。

3 个答案:

答案 0 :(得分:2)

无需在GROUP BY内加入汽车表。像这样重写查询:

SELECT cars.cars_id_primary, COALESCE(agg.open_defect_count, 0) AS open_defect_count
FROM cars
LEFT JOIN (
    SELECT cars_id, COUNT(*) AS open_defect_count
    FROM defect
    WHERE defect_status_id = 1
    GROUP BY cars_id
) AS agg ON cars.cars_id_primary = agg.cars_id
WHERE cars.stage_id != 5 
ORDER BY cars.updated_on

您还将需要创建索引。我建议从ix_defect(defect_status_id, cars_id)开始。

答案 1 :(得分:1)

您可以通过使用索引来提高性能。是否可以像下面的sql一样在cars_id_primary表的cars上创建索引并在cars_id的{​​{1}}上创建索引。然后,您可以尝试查询。

defect

答案 2 :(得分:0)

我无法理解您的问题,我对查询进行了一些更改,

SELECT cars.cars_id_primary ,COUNT(CASE WHEN (defect.defect_id_primary)>0 THEN 1 ELSE 0 
   END) AS `def_count`
FROM cars
LEFT JOIN defect ON cars.cars_id_primary = defect.cars_id 
WHERE cars.stage_id !=5 AND defect.defect_status_id =1 
GROUP BY cars.cars_id_primary
ORDER BY cars.updated_on

尝试