SQL结果有限制

时间:2014-04-14 10:18:22

标签: sql chat

我正在进行一次简单的聊天,并且只需要一种方法来获取10条消息" PR。谈话,但无法弄清楚如何这样做。

这是我已经尝试过的。 我的SQL:

SELECT c.* FROM chat c
INNER JOIN users su ON su.id = c.sender_user_id
INNER JOIN users ru ON ru.id = c.receiver_user_id
WHERE sender_user_id='1234' OR receiver_user_id='1234'
ORDER BY created ASC

现在我收到用户ID 1234的所有消息...但是我只想要10条消息。会话。

希望有意义

1 个答案:

答案 0 :(得分:1)

标准的SQL方法是使用窗口/分析函数:

SELECT t.*
FROM (SELECT c.*, su.name as sender_name, ru.name as receiver_name,
             row_number() over (partition by c.conversation order by c.created desc) as seqnum
      FROM chat c INNER JOIN
           users su
           ON su.id = c.sender_user_id INNER JOIN
           users ru
           ON ru.id = c.receiver_user_id
      WHERE sender_user_id = '1234' OR receiver_user_id = '1234'
     ) t
WHERE seqnum <= 10
ORDER BY created ASC;

请注意,您需要更好地在子查询中选择所需的列。使用*会导致列名重复。

编辑:

在MySQL中,您可以使用变量执行此操作:

SELECT t.*
FROM (SELECT c.*, su.name as sender_name, ru.name as receiver_name,
             (@rn := if(@c = c.conversation, @rn + 1,
                        if(@c := c.conversation, 1, 1)
                       )
             ) as seqnum
      FROM chat c INNER JOIN
           users su
           ON su.id = c.sender_user_id INNER JOIN
           users ru
           ON ru.id = c.receiver_user_id CROSS JOIN
           (SELECT @c := 0, @rn := 0) vars
      WHERE sender_user_id = '1234' OR receiver_user_id = '1234'
      ORDER BY c.conversation, c.created desc
     ) t
WHERE seqnum <= 10
ORDER BY created ASC;