我有两张桌子(汽车和car_images)
cars
----
id
brand
model
...
car_images
----------
id
car_id
name
...
每辆车都可以有多张图片......
用图像选择所有车辆的最佳方法是什么?
我是如何使用Native PHP PDO 来做的,但我不知道它是否是最好和最快的方式...
$sth = $dbh->query("SELECT * FROM cars");
$sth_images = $dbh->prepare("SELECT * FROM car_images WHERE car_id = :car_id");
while($row = $sth->fetch()){
$sth_images->execute(['car_id' => $row['id']]);
// ...
}
答案 0 :(得分:3)
你可以做LEFT JOIN,这样你就可以获得汽车,如果他们没有图像
SELECT * FROM cars LEFT JOIN car_images ON cars.id = car_images.car_id WHERE cars.id = :car_id
更新
如果您需要使用车辆ID或车辆图片ID,则上述将无法获得所需的结果。这会更好:
SELECT car_images.car_id, car_images.id AS image_id, car_images.name FROM cars LEFT JOIN car_images ON cars.id = car_images.car_id WHERE cars.id = :car_id
再次纠正:)