SQL:按消息排序不起作用

时间:2018-01-01 12:39:41

标签: php html sql sql-order-by

为什么这个SQL代码不能运行?

user_chats

             id | user_id | to_user_id |  ad_id  | timestamp
----------------+---------+------------+---------+-----------
              1 |       1 |      6     |   13    |  1513516133

user_messages

             id | chat_id |    text    | user_id | timestamp
----------------+---------+------------+---------+-----------
              1 |       1 |    Hello   |    1    |  1513516133
              2 |       1 |    Hi!     |    6    |  1513516754

我想获取聊天并通过user_messages.timestamp对它们进行排序。 我的SQL代码是:

SELECT user_chats.id,
       user_chats.timestamp,
       ad_id,
       title,
       user_chats.user_id
FROM   user_chats
       INNER JOIN ads
               ON ads.id = ad_id
WHERE  user_chats.user_id = "1"
        OR user_chats.to_user_id = "1"
ORDER  BY (SELECT id
           FROM   user_messages
           WHERE  chat_id = user_chats.id
           ORDER  BY user_messages.id DESC) 

1 个答案:

答案 0 :(得分:1)

问题是您在Order By子句中使用了子查询:因为这会为主查询中的每条记录返回多个结果,所以它不能用于排序主查询的结果。

我认为您正在尝试按每次聊天中的最新消息对结果进行排序,但只是加入user_messages表意味着您将获得重复项(每条消息每次聊天都会返回一次)。您可以通过加入内联视图来解决这个问题:

SELECT DISTINCT user_chats.id,
       user_chats.timestamp,
       ad_id,
       title,
       user_chats.user_id
FROM   user_chats
       INNER JOIN ads
               ON ads.id = ad_id
       LEFT JOIN   
         --in line view aliased 'UM' returns one row per chat_id in user_messages, with the last timestamp for that ID
                  (SELECT max(timestamp) LastMessage, 
                  chat_id
                  FROM user_messages
                  GROUP BY chat_id) um
               ON um.chat_id = user_chats.id
WHERE  user_chats.user_id = 1
        OR user_chats.to_user_id = 1
ORDER  BY um.LastMessage desc