用于JOIN查询的ORDER BY

时间:2016-06-09 04:34:31

标签: mysql sql join

我试图获取一组聊天的最后一条消息,以便我可以按最后更新的方式对它们进行排序。

我的查询中的所有内容都可以正常工作,但获取的邮件是第一个创建的邮件,而不是最后一条。

以下是查询中的示例:

SELECT
dc.id AS chat,
dcp.*,
dcm.created AS last_message_created
FROM data_chats dc
INNER JOIN data_chats_parties dcp ON dcp.chat=dc.id
AND dcp.member=1 -- current users id
AND dcp.status >= 1
INNER JOIN data_chats_messages dcm ON dcm.chat=dc.id AND dcm.active=1
WHERE dc.active=1
GROUP BY dcp.chat 
ORDER BY dcm.created DESC

我是否可以按data_chats_messages列的created对结果进行排序?

1 个答案:

答案 0 :(得分:2)

试试这个。这项工作在所有db

 SELECT
 dc.id AS chat,
 dcp.*,
 dcm.created AS last_message_created
 FROM data_chats dc
 INNER JOIN data_chats_parties dcp ON dcp.chat=dc.id
 AND dcp.member=1 -- current users id
 AND dcp.status >= 1
 INNER JOIN (select * from data_chats_messages order by created desc) dcm ON dcm.chat=dc.id AND dcm.active=1
 WHERE dc.active=1
 GROUP BY dcp.chat 
 ORDER BY dc.id DESC
  

这也可以,但不是在所有数据库中。

     

不知道在mariadb 5.5中工作

 select * from (SELECT
    data_chats.id AS chat,
    data_chats_parties.*,
    data_chats_messages.created AS last_message_created
  FROM data_chats
    INNER JOIN data_chats_parties
        ON data_chats_parties.chat=data_chats.id
            AND data_chats_parties.member=1 -- current users id
            AND data_chats_parties.status >= 1
    INNER JOIN data_chats_messages ON data_chats_messages.chat=data_chats.id AND data_chats_messages.active=1
  WHERE
    data_chats.active=1
  ORDER BY last_message_created DESC) a  GROUP BY chat