选择 PHP 和 MySQL 中包含其图片的汽车列表

Selecting a car listing with its images in PHP and MySQL

我有一个从 MySQL 数据库中选择 CAR 及其 IMAGES 的查询。

SELECT car.*, comments.*, person.*, body_type.* FROM car
INNER JOIN person
ON person.car_id = car.car_id 
INNER JOIN comments
ON comments.car_id = car.car_id 
INNER JOIN body_type
ON body_type.bodytype_id = car.bodytype_id
INNER JOIN images
ON images.car_id = car.car_id
ORDER BY added_on DESC 

然而,这实际上计算了来自 IMAGES 和 return 的图像的次数与来自 table 的图像的次数一样多。例如,如果 IMAGES table 中有五张图片,它将 return 一张 CAR 列表五次,当我真正想要显示这五张图片并将它们与一辆 CAR 使用 CAR ID。我注意到问题出在查询中,因为当我删除 INNER JOIN images ON images.car_id = car.car_id 时,汽车以正确的方式显示,除了没有图像。

您想获取每辆车的图像数量吗?也许这会对您有所帮助(未经测试):

SELECT car.*, comments.*, person.*, body_type.*, count(*) as countImages
FROM car
INNER JOIN person
ON person.car_id = car.car_id 
INNER JOIN comments
ON comments.car_id = car.car_id 
INNER JOIN body_type
ON body_type.bodytype_id = car.bodytype_id
INNER JOIN images
ON images.car_id = car.car_id
GROUP BY car.car_id
ORDER BY added_on DESC