SQL请求按用户ID

时间:2016-01-21 01:30:36

标签: php mysql sql

我有4张桌子:

  1. 会话
  2. conversations_users
  3. 消息
  4. 用户
  5. 会话结构表是:

    • id(主键)
    • 标题(会话标题)

    conversations_users结构表是:

    • id(主键)
    • conversationID(用户所在的会话ID)
    • userID(与会话ID关联的用户)

    消息结构表是:

    • id(主键)
    • 消息(消息文本)
    • conversationID(消息所在的会话ID)
    • senderID(发送邮件的用户ID)
    • 日期(邮件的时间戳)

    用户结构表是:

    • id(主键)
    • 用户名

    我想显示用户的所有会话(标题,最后消息和上次消息时间戳),以便只显示用户所在的会话。

    如何处理SQL请求?我猜它会是这样的:

    SELECT c.title, m.message, m.date 
    FROM conversation c
    INNER JOIN conversation_users cu
    ON ...
    INNER JOIN messages m
    ON ...
    INNER JOIN users u
    ON ...
    GROUP BY u.id
    

1 个答案:

答案 0 :(得分:1)

select usr.userID,
       cvs.title,
       msg.message,
       times.date 
from conversations_users usr
left join conversations cvs on usr.conversationID = cvs.id
left join messages msg on usr.conversationID = msg.conversationID
left join 
    (select usr.userID,
       MAX(msg.date) as date 
    from conversations_users usr
    left join messages msg on usr.conversationID = msg.conversationID
    group by usr.userID) times on times.userID= usr.userID and times.date=msg.date