【问题标题】:Is it possible to sort the columns of each row?是否可以对每一行的列进行排序?
【发布时间】:2018-04-20 17:57:14
【问题描述】:

我有一张桌子:

create table SomeTable( 
    N1 int(11) not null default 0,
    N2 int(11) not null default 0,
    N3 int(11) not null default 0,
    N4 int(11) not null default 0,
    N5 int(11) not null default 0
)

表格只有一行,如下所示:

N1 : 1
N2 : 2
N3 : 5
N4 : 0
N5 : 3

当我查询select * from table 时,我得到:

N1, N2, N3, N4, N5
 1,  2,  5,  0,  3

是否可以像这样对数据进行排序?

N3, N5, N2, N1, N4
 5,  3,  2,  1,  0

【问题讨论】:

  • select * from table order by second_col desc
  • 这种问题是恶劣设计的症状

标签: mysql sorting


【解决方案1】:

不幸的是,你不能这样做?你可以对行进行排序,但不能对列进行排序……你可以像这样指定所选列的顺序:

select N3, N5, N2, N1, N4 from SomeTable

【讨论】:

  • Yes))) 我知道这是可能的,但对于实际项目,这绝对是错误的方式......而且大而复杂的查询 - 这只是出现问题的迹象......
【解决方案2】:

您无法动态影响列名称,但您可以对值进行排序:

select
    greatest(N1, N2, N3, N4, N5) as col1,
    case greatest(N1, N2, N3, N4, N5)
        when N1 then greatest(N2, N3, N4, N5) 
        when N2 then greatest(N1, N3, N4, N5) 
        when N3 then greatest(N1, N2, N4, N5) 
        when N4 then greatest(N1, N2, N3, N5) 
        when N5 then greatest(N1, N2, N3, N4)
    end as col2,
    case greatest(N1 + N2, N1 + N3, N1 + N4, N1 + N5, N2 + N3, N2 + N4, N2 + N5, N3 + N4, N3 + N5, N4 + N5)
        when N1 + N2 then greatest(N3, N4, N5) 
        when N1 + N3 then greatest(N2, N4, N5)
        when N1 + N4 then greatest(N2, N3, N5)
        when N1 + N5 then greatest(N2, N3, N4)
        when N2 + N3 then greatest(N1, N4, N5)
        when N2 + N4 then greatest(N1, N3, N5)
        when N2 + N5 then greatest(N1, N3, N4)
        when N3 + N4 then greatest(N1, N2, N5)
        when N3 + N5 then greatest(N1, N2, N4)
        when N4 + N5 then greatest(N1, N2, N3)
    end as col3,
    case least(N1, N2, N3, N4, N5)
        when N1 then least(N2, N3, N4, N5) 
        when N2 then least(N1, N3, N4, N5) 
        when N3 then least(N1, N2, N4, N5) 
        when N4 then least(N1, N2, N3, N5) 
        when N5 then least(N1, N2, N3, N4)
    end as col4,
    least(N1, N2, N3, N4, N5) as col5
from table

这将适用于表中任意数量的行(而不是像您的情况那样只有 1 行)。

【讨论】:

  • 你会在实际项目中使用这个查询吗?)
  • 此外,您的查询是错误的(您必须根据值选择 1 条记录和适当的列名称,例如 N3, N5, N2, N1, N4 而不是 col1, col2, col3, col4, col5 就像您的查询一样。
  • 或者您可以修复损坏的桌子设计
  • @Strawberry 我认为这也是一个损坏的查询要求。我从未听说过需要有序列的应用程序。我觉得这个代码不干净,但我这样做主要是为了反驳弗拉德的论点,即这是不可能的……我喜欢用代码做“不可能”的事情。
  • @Bohemian 好吧,今晚的彩票号码的 sproc 怎么样? ;-)
猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
相关资源
最近更新 更多