Each table (table1 & table2) has its own DATETIME field.
I'm trying to catch id's of the two tables and order them by their DATETIME field.
Example:
Table 1 Table 2
------------ -------------
id | datetime1 id | table1id | datetime2
------------------------ -----------------------
1 | 2014-09-21 20:31:26 1 | 2 | 2014-09-21 20:31:29
2 | 2014-09-21 20:31:27 2 | 3 | 2014-09-21 20:31:30
3 | 2014-09-21 20:31:28
Table 3
------------
id | user
------------------------
2 | phil
3 | nathalie
My output isn't ordered properly with this query:
SELECT *
FROM (
SELECT
1 AS selection,
table1.id, table1.datetime1,
table2.datetime2
table3.user
FROM Table1
LEFT OUTER JOIN table2
ON table1.id = table2.table1id
LEFT OUTER JOIN table3
ON table1.id = table3.id
UNION ALL
SELECT
2 AS selection,
table1.id, table1.datetime1,
table2.datetime2
table3.user
FROM Table1
INNER JOIN table2
ON table1.id = table2.table1id
INNER JOIN table3
ON table1.id = table3.id
) AS query
ORDER BY table1.datetime1 DESC, table2.datetime2 DESC
Desired data:
from table 2 id: 2, 1,
from table 1 id: 3, 2, 1
So: 2, 1, 3, 2, 1
////EDIT
To people who could be struggling with long and complex MySQL request, please try it in PhpmyAdmin! It will tell you the error!
////EDIT