PDA

View Full Version : Help with a nested MySQL query!


bigmattyh
05-04-2002, 12:57 AM
Okay, so I'm a pretty experienced MySQL programmer, but this problem has stumped me.

I'm getting some funky results when working with a nested MySQL query. It goes something like this:
$cars = $DB_site->query("SELECT * FROM cars");
while ($car = $DB_site->fetch_array($cars)) {
$passengers= $DB_site->query("SELECT * FROM passengers WHERE car.id = '$car[id]'");
while ($passenger= $DB_site->fetch_array($passengers)) {
// Do stuff with data
// Display the data
}
}
I'm getting the list of cars to come out right. But the list of passengers for car #1 is getting returned for every car.

Has anyone encountered a similar problem to this, and does anyone have a solution?

bigmattyh
05-04-2002, 02:44 AM
Problem solved. I discoverred the wonder that is "unset()".

Mark Hensler
05-04-2002, 11:00 PM
Ack! Avoid nested queries when possible. Use a JOIN query instead. You'll save processing time and system resources.

something like this:

SELECT cars.id as cid, cars.field2 as cfield2, passengers.id as pid, passengers.field2 as pfield2 FROM cars c LEFT JOIN passengers p ON cars.id=passwngers.car_id ORDER BY cars.field3 ASC, passengers.field3 ASC