那个设定
我有一个包含两个表的数据库。其中一个用于收件箱消息 ( inbox
),另一个用于发件箱消息 ( outbox
)。它们都有相同的结构和一些记录。
+------------------------------------------------------------+
| inbox |
+------------------------------------------------------------+
| messageID | from | to | messageText | timestamp |
+------------------------------------------------------------+
| 1 | userA | userB | sometext | 2013-06-19 10:30 |
| 2 | userB | userC | sometext | 2013-06-19 10:40 |
| 3 | userC | userA | sometext | 2013-06-19 10:50 |
+------------------------------------------------------------+
和
+------------------------------------------------------------+
| outbox |
+------------------------------------------------------------+
| messageID | from | to | messageText | timestamp |
+------------------------------------------------------------+
| 1 | userA | userC | sometext | 2013-06-19 10:20 |
| 2 | userC | userB | sometext | 2013-06-19 10:30 |
| 3 | userB | userA | sometext | 2013-06-19 10:35 |
+------------------------------------------------------------+
问题
我需要从特定用户的每个对话中选择每条最后一条消息(在这种情况下 - 我想从 userA 的对话中检索每条最后一条消息)在消息所在的任何表中 - 收件箱或发件箱。我已设法使用以下查询从收件箱和发件箱中为每个对话选择最后一条消息:
SELECT * FROM
(
SELECT from, to, timestamp, messageText, messageID
FROM inbox
WHERE to = 'userA'
ORDER BY timestamp DESC
)
AS tmp_table GROUP BY from
UNION
SELECT * FROM
(
SELECT from, to, timestamp, messageText, messageID
FROM outbox
WHERE from = 'userA'
ORDER BY timestamp DESC
)
AS tmp_table GROUP BY to
ORDER BY timestamp DESC
因此,现在我需要检查哪条消息较新 - 收件箱中的消息或发件箱中的消息(当然,如果两个用户之间的两个表中都存在消息)并且只返回最新消息。
或者也许我的方法是彻头彻尾的愚蠢 - 请评论:D 谢谢。