【问题标题】:select distinct and order by multiple smallint columns选择不同的并按多个 smallint 列排序
【发布时间】:2017-05-05 14:22:41
【问题描述】:

widthheight 列是 smallint(6)
我想从width 中选择distinct 值,按width asc 排序,然后按height asc 排序。 这是我的尝试:

- $sql = "select * from banners group by width order by width, height asc";  
- $sql = "select * from banners group by width order by width asc, height asc";  
- $sql = "select * from banners group by width order by width asc, height";  

没有任何作用。选择按宽度排序,但按高度不正确。

【问题讨论】:

  • 你能展示一些示例数据吗?
  • 请期待输出
  • 这个ans可以帮助你stackoverflow.com/a/42719808/2286537
  • 为什么是group by width
  • @Forward,因为我只需要来自 width 的不同值。

标签: php mysql


【解决方案1】:

使用group by而不是distinct是不合适的(并且不允许从mysql 5.7开始)只选择没有明确名称的一行

您应该在选择和聚合函数中使用显式列名来表示不在 group by 中的列名

通过这种方式,您可以真正控制所选值和结果行的顺序

例如:

select distinct width,  height 
from banners 
order by width, height asc

select  width,  max(height )
from banners 
group by width
order by width, height asc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多