从两个表中选择并按日期时间戳排序

时间:2014-04-25 19:00:29

标签: mysql select union

我有两个类似于下面的MySQL表:

MESSAGES_IN
messageID
receivedDate
message

MESSAGES_OUT
messageID
sentDate
message

基本上,我想从两个表中选择消息并按各自的日期排序。例如,如果数据集是:

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

然后我希望输出为:

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

我已尝试过以下查询,但我收到的错误是我的ORDER BY是一个未知栏:

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

谢谢!

2 个答案:

答案 0 :(得分:2)

使用UNION时,MySQL将使用第一个查询中的列名,因此只需使用ORDER BY子句中的第一个查询列名称:

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

使用这样的别名来保持列名有意义是很常见的:

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

此外,您可能希望UNION ALL避免在结果中丢失重复的行。

答案 1 :(得分:0)

由于列名不同,您可以使用" ORDER BY 1"这意味着第一栏。

(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

我相信MySQL也可以在这种情况下使用别名,所以你可以替换" 1" with messageDate。