这是我的 MySQL 数据库结构:
Recipents (id, converstation_id, user_id)
Conversations (id, user_start)
Messages (id, user_id, message, conversation_id, time)
我要做的是提取由特定用户发起的所有对话 ID,或者他是其中一个对话的接收者。并按最后一条消息排序。
我怎样才能做到这一点?
以下查询将起作用。您必须用REQUESTED_USER_ID
有效的用户 ID 替换。注意连接两个子查询结果的 SQL 中的 UNION 语句。然后将来自 UNION 的结果包装在另一个 SELECT 中以实现按开始时间排序。
SELECT
conversation_id
FROM (
SELECT
c.id AS conversation_id,
m.time AS start
FROM Conversations c
JOIN Messages m ON m.conversation_id = c.id
WHERE c.user_start = REQUESTED_USER_ID
UNION
SELECT
c.id AS conversation_id,
m.time AS start
FROM Conversations c
JOIN Recipents r ON c.id = r.user_id
JOIN Messages m ON m.conversation_id = c.id
WHERE r.user_id = REQUESTED_USER_ID
) result
ORDER BY start DESC;