MySQL will use the column names from the first query when using UNION
, so just use the first query's column name in the ORDER BY
clause:
SELECT i.receivedDate, i.message
FROM MESSAGES_IN i
UNION ALL
SELECT o.sentDate, o.message
FROM MESSAGES_OUT o
ORDER BY receivedDate
It's common to use an alias like this to keep the column name meaningfull:
SELECT i.receivedDate AS sendreceiveDate, i.message
FROM MESSAGES_IN i
UNION ALL
SELECT o.sentDate, o.message
FROM MESSAGES_OUT o
ORDER BY sendreceiveDate
Also, you probably want UNION ALL
to avoid losing duplicate rows in the results.