合并来自不同表的2列

时间:2012-10-23 14:37:55

标签: mysql

我有2张桌子。

1.Message - Sender_Number,SMS,DateTime.
2.Replies - Receiver_Number,SMS,DateTime.

我想组合所有列并将2个DateTime列合并为一个列并按时间顺序排列。

例如:

Messages Table:
123 | Hello there. | 2012-10-22 3:50
121 | HI I like U..| 2012-10-22 9:10

Replies Table:
123 | how are u... | 2012-10-22 5:50
121 | HI I like U2 | 2012-10-22 9:30

DESIRED OUTPUT (In 1 table):
123 | Hello there. | 2012-10-22 3:50 
123 | how are u... | 2012-10-22 5:50 
121 | HI I like U..| 2012-10-22 9:10 
121 | HI I like U2 | 2012-10-22 9:30 

2 个答案:

答案 0 :(得分:2)

SELECT *
FROM
(
    SELECT col1, col2, col3 FROM messages
    UNION ALL
    SELECT col1, col2, col3 FROM replies
) x
ORDER BY col3

SQLFiddle Demo

答案 1 :(得分:0)

您需要UNION

就像这样

SELECT * FROM (
SELECT Sender_Number,SMS,DateTime FROM Messages
UNION 
SELECT Receiver_Number,SMS,DateTime FROM Replies
)
ORDER BY DateTime

此外,我不会调用列DateTime,因为它是MySQL中的数据类型。它可能会导致问题