我有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
但这似乎给出了错误的结果
答案 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