【问题标题】:order and group mysql订购和分组mysql
【发布时间】:2018-11-03 04:55:46
【问题描述】:

我是查询mysql的初学者

我有这样的表格行和值

enter image description here

我想从表格中选择:按 ID 降序排列并按电话分组 所以结果会是这样的

enter image description here

请任何人帮助我..

我已经这样放了

select * from messages where 1 group by phone order by ID desc

但是错了

谢谢

【问题讨论】:

标签: mysql select greatest-n-per-group


【解决方案1】:

要获取每个电话属性的最新消息,您可以使用自我加入

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

【讨论】:

    【解决方案2】:

    试试下面的查询

    select phone, text from messages group by phone order by id DESC
    

    【讨论】:

    • 因为文本不是聚合函数,所以运行时会报错。
    • 我在哪里写了文本作为聚合函数?
    • 我的意思是应该像电话一样按子句分组
    • @RajatJaiswal - 出于什么目的?有问题的是,它提到结果应该是电话分组。如果我没看错:)
    【解决方案3】:

    它不适用于 group by 而不是这个 try 下面的查询

    SELECT text,phone
    FROM @tblPhone tmp
    WHERE id = (SELECT MAX(Id) FROM @tblPhone tmp1 WHERE tmp1.PHONE = tmp.Phone)
    ORDER BY Id desc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      相关资源
      最近更新 更多