我是查询mysql的初学者
我有这样的表行和值
我想从表中选择:按 ID 降序排序并按电话分组 所以结果会是这样
请任何人帮助我..
我已经这样写了
select * from messages where 1 group by phone order by ID desc
但这是错误的
谢谢
最佳答案
要获取每个电话属性的最新消息,您可以使用自连接
select a.*
from messages a
join (
select phone, max(id) id
from messages
group by phone
) b on a.phone = b.phone and a.id = b.id
或者使用左连接
select a.*
from messages a
left join messages b on a.phone = b.phone and a.id < b.id
where b.phone is null
关于mysql - 排序和分组 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50501282/