这是我的MySQL数据库结构:
Recipents (id, converstation_id, user_id)
Conversations (id, user_start)
Messages (id, user_id, message, conversation_id, time)
我要做的是拉出由特定用户或启动的所有会话ID,他是其中一个会话的收件人。并按最后一条消息排序。
我该怎么做?
答案 0 :(得分:1)
以下查询将有效。您必须使用有效的用户ID替换REQUESTED_USER_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;
玩得开心! :)