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

标签 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            |
+----------------+--------------+

最佳答案

我认为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;

关于mysql - 为单个 mysql 表中的每个最大列选择 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46865697/

相关文章:

sql - 带条件搜索字符串

sql - 在目标表不存在的地方定义 FK

sql - PostgreSQL 错误 : function expression in FROM cannot refer to other relations of same query level

php - SQL - 如何避免为并发连接选取同一行?

php - 执行多个查询然后输出为数组

sql 通过多个 postgres 数据库进行选择

mysql - 在单列中存储随机数量的外键和值[关系数据库设计]

mysql - 截断不正确的日期时间值 mysql

php - 在 mysqli 准备中提交表单后显示成功消息

mysql - 对 MySQL 的攻击——以及如何防止它?