[英]How do I get a count of associated rows in a left join in MySQL?
I have two tables, a vehicle
table with columns: 我有两个表,一个带有列的vehicle
表:
id
stock
year
make
model
and an images
table with columns: 和带有列的images
表:
id
vehicle_id
name
caption
default tinyint(1)
I am trying to list the vehicle's information, its default image, and a total count of images the vehicle has. 我正在尝试列出车辆的信息,其默认图像以及车辆具有的图像总数。 Currently I am using the following SELECT
statement: 目前,我正在使用以下SELECT
语句:
SELECT vehicle.id, vehicle.stock, vehicle.year,
vehicle.make, vehicle.model, images.name,
COUNT(images.id)
FROM vehicle
LEFT JOIN images
ON vehicle.id = images.vehicle_id
I initially was using: 我最初使用的是:
ON vehicle.id = images.vehicle_id AND images.default = 1
but then the images count would only be 1 or 0 depending if there was a default image in the database. 但是根据数据库中是否有默认图像,图像计数将仅为1或0。 I have tried using UNION
and other SELECT
statements but I am still unable to get a proper result. 我尝试使用UNION
和其他SELECT
语句,但是仍然无法获得正确的结果。 Do I need to use two SELECT
statements or is there another way to handle it with JOIN
or UNION
? 我需要使用两个SELECT
语句还是使用JOIN
或UNION
处理它的另一种方法?
SELECT
`vehicle`.`id`,
`vehicle`.`stock`,
`vehicle`.`year`,
`vehicle`.`make`,
`vehicle`.`model`,
`images`.`name`,
(
SELECT COUNT(*)
FROM `images`
WHERE `vehicle_id` = `vehicle`.`id`
) AS `image_count`
FROM `vehicle`
LEFT JOIN `images`
ON `images`.`vehicle_id` = `vehicle`.`id`
WHERE `images`.`default`
In the way the anser suggests, you get repeated values of "vehicle". 按照分析者的建议,您将获得“车辆”的重复值。 A better way, is to group results. 更好的方法是对结果进行分组。 Try without the JOIN : 尝试不使用JOIN:
SELECT
`vehicle`.`id`,
`vehicle`.`stock`,
`vehicle`.`year`,
`vehicle`.`make`,
`vehicle`.`model`,
`images`.`name`,
(
SELECT COUNT(*)
FROM `images`
WHERE `vehicle_id` = `vehicle`.`id`
) AS `image_count`
FROM `vehicle`
WHERE `images`.`default`
Task : Print 3 columns table: 任务 :打印3列表格:
Expected output (just an example) : 预期输出(仅作为示例) :
+----------------------+----------------+--------------+
| title | comments_count | images_count |
+----------------------+----------------+--------------+
| BMW X6 | 35 | 9 |
| Audi A6 | 3 | 5 |
| Volkswagen Passat B6 | 78 | 6 |
| Volkswagen Passat B5 | 129 | 4 |
+----------------------+----------------+--------------+
Solution : 解决方案 :
SELECT
vehicles.title,
(SELECT COUNT(*) FROM comments WHERE vehicles.id = comments.vehicle_id) AS comments_count,
(SELECT COUNT(*) FROM images WHERE vehicles.id = images.vehicle_id) AS images_count
FROM vehicles
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.