消息格式的sql ORDER

时间:2013-02-25 12:54:40

标签: sql sql-server tsql

我有一个消息图标,点击后会打开类似Facebook的消息divdiv会自动滚动到底部。在此div上,我收到了最后25条消息。问题是我希望消息从div底部的最新消息开始排序。我有两个订单列: id ,它是自动增量, dt 是日期时间。

我已经尝试了ORDER BY的每一个组合,我无法得到它。

SELECT TOP 25 
    rec, 
    sender, 
    message, 
    CONVERT(varchar(20),dt,120) AS date 
FROM dbo.messages 
WHERE (rec='$user[name]' OR sender='$user[name]') 
ORDER BY id DESC, dt ASC

没有底线,但理论上SELECT BOTTOM 25 * ORDER BY id会很完美。

2 个答案:

答案 0 :(得分:0)

您应该只能按日期时间列(降序)排序,然后拉出前25名。我已经修改了您的查询。

SELECT TOP 25 
rec, sender, message, CONVERT(varchar(20),dt,120) AS date 
FROM dbo.messages
WHERE (rec='$user[name]' OR sender='$user[name]') 
ORDER BY dt DESC

答案 1 :(得分:0)

获取SELECT BOTTOM 25 * ORDER BY id(即; TOP 25 ORDER BY id DESC

;with cte as (
  select top 25 
        id,
        rec, 
        sender, 
        message, 
        dt
  from dbo.messages 
  where (rec='$user[name]' OR sender='$user[name]') 
  order by id desc
)
select rec, sender, message, convert(varchar(20),dt,120) date
from cte
order by id,dt -- as required here