I'm getting a weird result from a quite long query, which I will simplify here:
DROP TEMPORARY TABLE IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS
(SELECT
parent.id as parent_id,
times.a_time,
times.sequence,
FROM times
LEFT JOIN parent ON times.parent_id=parent.id
WHERE times.stop_id=10);
DROP TEMPORARY TABLE IF EXISTS table2;
CREATE TEMPORARY TABLE table2 AS
(SELECT
parent.id as parent_id,
times.b_time,
times.sequence,
FROM times
LEFT JOIN parent ON times.parent_id=parent.id
WHERE times.stop_id=15 );
--here comes PDO->exec();
SELECT table1.*, table2.b_time
FROM table1
LEFT JOIN table2 ON table1.parent_id=table2.parent_id
WHERE table2.parent_id IS NOT NULL AND table1.sequence<table2.sequence
ORDER BY table1.a_time
I'm testing the query using EMS MySQL Manager 2007, and in PHP I'm using PDO query.
In order to get the final result, (I know that PDO doesn't support running this full query at once and giving back the result set), I run PDO->exec()
after temporary tables creation (see comment in the query), and then I run PDO->query()
on the last SELECT
:
$db = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$tempTablesSQL='DROP TEMPORARY TABLE IF EXISTS...'; //create temporary tables
$db->exec($tempTablesSQL);
$sql='SELECT table1.*, table2.b_time ...'; //JOIN and SELECT the results
$results=array();
foreach($db->query($sql) as $row){
$results[]=$row;
}
print_r($results);
In MySQL Manager I run the whole query at once, and for those specific IDs I'm getting 29 rows as result (which is correct, because the records are inserted from a previously parsed file, and by comparing the results to the file I know they are good).
But in PHP, I'm getting only 25 results, and totally wrong values for b_time
.
So, my questions are:
why do I get wrong results?
is my approach of calling this query wrong (in PHP)?
Any help is appreciated.
--EDIT--
It's not just PDO, I tried with mysqli_multi_query, I'm getting the same wrong results.
One important thing I noticed is: if I use regular tables instead of the temporary, the results are fine.