为单个mysql表中的每个最大列选择ID

时间:2017-10-21 16:55:45

标签: mysql sql

我的表### inf_simpleranks

+-----+--------------+----------+---------+----------+
| uid | style_normal | style_sw | style_w | style_ad |
+-----+--------------+----------+---------+----------+
|   1 |          159 |        9 |     164 |      195 |
|   2 |           46 |       39 |      55 |      159 |
|   3 |          188 |       28 |     171 |      174 |
|   4 |          135 |       32 |     151 |       63 |
|   5 |            3 |      156 |     173 |      197 |
+-----+--------------+----------+---------+----------+

我可以获得每列的最大值

select 
  a.uid,
  a.style_normal
from
  inf_simpleranks a
  inner join (
    select max(style_normal) as style_normal
    from inf_simpleranks
  ) b on a.style_normal = b.style_normal;


+-----+--------------+
| uid | style_normal |
+-----+--------------+
|   3 |          188 |
+-----+--------------+

这个

+-----+----------+
| uid | style_sw |
+-----+----------+
|   5 |      156 |
+-----+----------+

有时UID会匹配

+-----+----------+
| uid | style_ad |
+-----+----------+
|   5 |      197 |
+-----+----------+

但是我试图把它变成一个查询,所以它看起来像这样:

+----------------+--------------+
| MAX            | UID          |
+----------------+--------------+
| style_normal   | 3            |
| style_sw       | 5            |
| style_w        | 5            |
| style_ad       | 5            |
+----------------+--------------+

1 个答案:

答案 0 :(得分:3)

我认为union all可能是最好的方法:

(select 'style_normal' as which, style_normal, uid
 from inf_simpleranks
 order by style_normal desc
 limit 1
) union all
(select 'style_sw' as which, style_sw, uid
 from inf_simpleranks
 order by style_sw desc
 limit 1
) union all
. . .

如果您的数据不是太大(由于group_concat()的内部限制而您可以在列中显示值,则可以执行以下操作:

select substring_index(group_concat(uid order by style_normal desc), ',', 1) as style_normal,
       substring_index(group_concat(uid order by style_sw desc), ',', 1) as style_sw,
       . . .
from inf_simpleranks;