Question

I have two MySQL tables similar to below:

MESSAGES_IN
messageID
receivedDate
message

MESSAGES_OUT
messageID
sentDate
message

Basically, I want to select messages from both tables and order them by their respective dates. For example, if the data set were:

MESSAGES_IN
1  2014-04-24 12:26:33  Test message inbound
2  2014-04-24 19:12:15  Another test message inbound

MESSAGES_OUT
1  2014-04-24 12:31:33  Test message outbound
2  2014-04-24 19:16:15  Another test message outbound

Then I want the output to be:

2014-04-24 12:26:33  Test message inbound
2014-04-24 12:31:33  Test message outbound
2014-04-24 19:12:15  Another test message inbound    
2014-04-24 19:16:15  Another test message outbound

I've attempted the query below but I'm getting error that my ORDER BY is an unknown column:

SELECT i.receivedDate, i.message
FROM MESSAGES_IN i
UNION
SELECT sentDate, o.message
FROM MESSAGES_OUT o
ORDER BY receivedDate, sentDate;

Thank you!

Was it helpful?

Solution

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.

OTHER TIPS

Since column names are different, you can use "ORDER BY 1" which means first column.

(SELECT i.receivedDate as messageDate, i.message
FROM MESSAGES_IN i )
UNION
( SELECT o.sentDate as messageDate, o.message
FROM MESSAGES_OUT o )
ORDER BY 1

I believe MySQL can use the alias in this case too, so you can replace "1" with messageDate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top