构建mysql聊天查询显示顺序

时间:2013-01-18 01:28:54

标签: mysql

我正在使用一个小型聊天应用程序,但是仍然坚持订购并限制从DB显示的结果。我想将结果限制为20并在HTML容器DIV的底部显示最新结果,我需要获得聊天表的最高ID - 20然后显示这些结果。这是我当前的查询

SELECT chat_box.*,

(SELECT MAX(chat_id) AS last FROM chat_box) AS last
FROM chat_box 
ORDER BY chat_id ASC
LIMIT last,20

2 个答案:

答案 0 :(得分:0)

试试这个

 SELECT chat_box.*, MAX(chat_id) AS last FROM chat_box 

ORDER BY chat_id ASC
LIMIT 20

或者如果你想在查询中看到正确的话,你应该这样做

   SELECT chat_box.*,

 (SELECT MAX(chat_id) AS last FROM chat_box LIMIT last,20) AS last2
    FROM chat_box 
 ORDER BY chat_id ASC

答案 1 :(得分:0)

如果您只想显示表格的最后20个条目,则不需要MAX

SELECT `you`, `should`, `use`, `a`, `column`, `list`
FROM chat_box
ORDER BY chat_id DESC
LIMIT 20

<强>更新

SELECT `you`, `should`, `use`, `a`, `column`, `list`
FROM chat_box
WHERE chat_id > (SELECT MAX(chat_id) - 20 FROM chat_box)