从数据库中提取消息线程列表数据

时间:2013-01-08 22:58:32

标签: php mysql database

这是我的MySQL数据库结构:

Recipents (id, converstation_id, user_id)

Conversations (id, user_start)

Messages (id, user_id, message, conversation_id, time)

我要做的是拉出由特定用户启动的所有会话ID,他是其中一个会话的收件人。并按最后一条消息排序。

我该怎么做?

1 个答案:

答案 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;

玩得开心! :)