如何根据一行中的数列获取mysql-table列的最小值

How to get the minimum value of a mysql-table column based on the number sequence in a row

我有一个 mysql-table(结果),其中有六列,如下所示:

+----+-------+-------+-------+-------+-------+
| id | can_1 | can_2 | can_3 | can_4 | can_5 |
+----+-------+-------+-------+-------+-------+
|  1 |     1 |     0 |     2 |     4 |     3 |
+----+-------+-------+-------+-------+-------+
|  2 |     2 |     1 |     5 |     3 |     4 |
+----+-------+-------+-------+-------+-------+
|  3 |     3 |     1 |     0 |     0 |     0 |
+----+-------+-------+-------+-------+-------+
|  4 |     0 |     2 |     1 |     0 |     3 |
+----+-------+-------+-------+-------+-------+

我正在尝试根据每行中存储的值从 can_1 列中获取最小值 大于 1 的行。

例如:can_1 需要 return 行 (id) 2 和 3,因为 2 是第 2 行的最小值,而 3 是第 3 行的最小值。

正在使用

SELECT id FROM results WHERE can_1 = (SELECT MIN(can_1) FROM results);

returns

+----+
| id |
+----+
|  2 |
+----+

这是可以理解的 - MIN-value 检查整个列 (can_1) 中大于 1 的最小值,在 can_1 情况下为 2。但是我该如何组合它,以便 entire 行(覆盖所有列)的最小值确定 can_1 列的 return 的最小值,即。结果是这样吗?

+----+
| id |
+----+
|  2 |
+----+
|  3 |
+----+

你可以用函数 LEAST():

select id
from tablename
where can_1 > 1
and can_1 = least(
  can_1, 
  case when can_2 <= 1 then can_1 + 1 else can_2 end, 
  case when can_3 <= 1 then can_1 + 1 else can_3 end, 
  case when can_4 <= 1 then can_1 + 1 else can_4 end, 
  case when can_5 <= 1 then can_1 + 1 else can_5 end
)

参见demo
结果:

| id  |
| --- |
| 2   |
| 3   |