MySQL按照上次消息发送时间排序进行团队聊天

时间:2015-01-22 08:43:10

标签: mysql sql-order-by

我有2个表,负责团队和团队消息。让我们说他们的结构是这样的:

teams
team_id |   team_name
--------+------------
      1 |  First team
      2 | Second team
      3 |  Third team

team_messages
team_message_id | team_id | message_text | send_time
----------------+---------+--------------+----------
              1 |       1 |              |         1
              2 |       3 |              |         2
              3 |       2 |              |         3

我想展示团队的方式是:

team_id | team_name
--------+------------
      2 | Second Team
      3 | Third team
      1 | First team

所以基本上我需要显示在该团队desc中按最后一条消息排序的所有团队。我试过的是

SELECT * FROM teams a
ORDER BY
(
    SELECT `send_time`
    FROM team_messages b
    ORDER BY b.`t_message_id` DESC
    LIMIT 1
) DESC

但这似乎给出了错误的结果

2 个答案:

答案 0 :(得分:1)

尝试

select * from teams a join team_messages b on a.team_id = b.team_id
order by b.send_time desc

答案 1 :(得分:1)

您的原始查询仅为所有记录选择一行,即最新消息时间。尝试像

这样的东西
SELECT a.*, (
    SELECT max(send_time)
    FROM team_messages b
    WHERE b.team_id = a.team_id
    ) as ord
FROM teams a
ORDER BY ord DESC

如果MySQL不按顺序允许别名,则可能需要将其移动到派生表中:

SELECT * FROM (
   SELECT a.*, (
     SELECT max(send_time)
     FROM team_messages b
     WHERE b.team_id = a.team_id
     ) as ord
   FROM teams a
)
ORDER BY ord DESC