1

I have two tables (cars and car_images)

cars
----
id
brand
model
...

car_images
----------
id
car_id
name
...

Every car can have multiple images ...

What is the best way to select all cars with their images ?

That's how I do it with Native PHP PDO, but I don't know if it's the best and fastest way ...

$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']]);
    // ...
}
1
  • use LEFT JOIN instead Commented Mar 10, 2017 at 14:55

1 Answer 1

3

You can do LEFT JOIN so you get cars also if they dont have images

SELECT * FROM cars LEFT JOIN car_images ON cars.id = car_images.car_id WHERE cars.id = :car_id

UPDATE

If you need to work with either car id or car image id, above will not have the desired result. This would be better:

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

Corrected that again :)

Sign up to request clarification or add additional context in comments.

2 Comments

But this query will results with a lot of repeated data !!
The first query would also return unuseful data with an overridden id. The second query would return a list of car id, image id and image name based on the car id you pass to PDO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.