I got my table called cars , and the second table called uploads which has a car_id field, I can LEFT JOIN this, so the uploads.car_id = cars.id, the problem comes, and uploads table, for more than one record for certain car id, what then? I have to use second query in a loop like this?
$cars = $PDO->query("SELECT * FROM `cars`")->fetchAll();
foreach($cars as $car)
{
$uploads = $PDO->query("SELECT * from uploads WHERE id = " . (int)$car['id'])->fetch();
echo 'My upload file name:' . $uploads['hash'];
}
? Its not a good idea, because $cars query may return more than 500 records at once… So it will be a huge performance lost.
So my question is, what can I do in this case, to prevent the query in the loop?
You can use the GROUP BY and GROUB_CONCAT sql functions to get what you want in one query with better performance
try :