尝试过一百万种不同的方法后,我似乎无法正确选择“count_lonely_vehicles”。'count_lonely_vehicles' 子选择当前只计算一个车辆 ID 关联的照片总数,但不像其他选择那样对经销商.id 进行分组。
dealerships (has many vehicles)
-----------
id | name
vehicles (has many photos and belongs to dealership)
--------
id | dealership_id
photos (belongs to vehicle)
------
id | vehicle_id
SELECT DISTINCT
dealerships.id,
dealerships.name,
COUNT(photos.id) AS 'count_photos',
FLOOR(COUNT(photos.id) / COUNT(DISTINCT vehicles.id)) AS 'photos_per_vehicle',
(
SELECT COUNT(*)
FROM (
SELECT COUNT(photos.vehicle_id) AS 'count'
FROM photos
GROUP BY photos.vehicle_id
HAVING COUNT(photos.vehicle_id) = 1
) AS tbl
) AS 'count_lonely_vehicles'
FROM dealerships
JOIN vehicles ON vehicles.dealership_id = dealerships.id
JOIN photos ON photos.vehicle_id = vehicles.id
GROUP BY dealerships.id
ORDER BY count_photos DESC
因此,当在模板中循环遍历经销商数组并吐出“count_lonely_vehicles”时,它始终是相同的数字。预期的行为是收集照片记录的数量,每个经销商只有一个 vehicle_id 关联。
我怎样才能重写这个查询来完成这个?
编辑:已回答
在所选答案的帮助下,这个查询终于奏效了。还必须修复一些在所选答案中错误的字段名称。
SELECT
dealerships.id,
dealerships.name,
COUNT(photos.id) AS 'count_photos',
FLOOR(COUNT(DISTINCT photos.id) / COUNT(DISTINCT vehicles.id)) AS 'photos_per_vehicle',
l.num_lonely
FROM dealerships
JOIN vehicles ON vehicles.dealership_id = dealerships.id
JOIN photos ON photos.vehicle_id = vehicles.id
LEFT OUTER JOIN (
SELECT
v.dealership_id,
COUNT(*) AS num_lonely
FROM dealerships d
JOIN vehicles v ON v.dealership_id = d.id
JOIN (
SELECT p.vehicle_id
FROM photos p
GROUP BY p.vehicle_id
HAVING COUNT(*) = 1
) p ON p.vehicle_id = v.id
GROUP BY d.id
) l ON vehicles.dealership_id = l.dealership_id
GROUP BY dealerships.id
ORDER BY count_photos DESC