我有两个表,一个vehicle
表,其中包含列:
id
stock
year
make
model
和包含列的images
表:
id
vehicle_id
name
caption
default tinyint(1)
我正在尝试列出车辆的信息,默认图像以及车辆的图像总数。目前我正在使用以下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
我最初使用的是:
ON vehicle.id = images.vehicle_id AND images.default = 1
但是图像计数只有1或0,具体取决于数据库中是否有默认图像。我尝试过使用UNION
和其他SELECT
语句但我仍然无法获得正确的结果。我是否需要使用两个SELECT
语句,还是有另一种方法可以使用JOIN
或UNION
来处理它?</ p>
答案 0 :(得分:30)
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`
答案 1 :(得分:5)
在答案建议的方式中,你会得到“车辆”的重复值。更好的方法是对结果进行分组。尝试没有加入:
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`
答案 2 :(得分:3)
任务:打印3列表:
预期输出(仅举例):
+----------------------+----------------+--------------+
| title | comments_count | images_count |
+----------------------+----------------+--------------+
| BMW X6 | 35 | 9 |
| Audi A6 | 3 | 5 |
| Volkswagen Passat B6 | 78 | 6 |
| Volkswagen Passat B5 | 129 | 4 |
+----------------------+----------------+--------------+
<强>解决方案强>:
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