gpt4 book ai didi

mysql - 如何从mysql中的单行中获取最小值

转载 作者:行者123 更新时间:2023-11-29 07:21:13 25 4
gpt4 key购买 nike

我想知道如何从单行中获取最小数值,例如:

我的 table :

|col a|col b|col c|some other col|some other col|
-------------------------------------------------
| 13 | 2 | 5 | 0 | 0 |

问题是:如何从 col a、col b 和 col c 中获取最小值(我想忽略其他列。

我已经尝试过这个: 从表 WHERE id=0 中选择 MIN(col a, col b, col c)

但这显然行不通。

任何帮助将不胜感激。

最佳答案

MySQL 中正确的函数是 least():

SELECT least(cola, colb, colc) 
FROM table
WHERE id = 0;

非常重要:这假设所有值都是非 NULL。如果您有 NULL 值,则 least() 返回 NULL

如果您需要考虑这一点,可以使用 coalesce() 。 。 。一种方法是使用最高值:

SELECT nullif(least(coalesce(cola, 999999), coalesce(colb, 999999), coalesce(colc, 999999)), 999999)
FROM table
WHERE id = 0;

或者,对列中的值使用 coalesce():

SELECT least(coalesce(cola, colb, colc), coalesce(colb, colc, cola), coalesce(colc, colb, cola))
FROM table
WHERE id = 0;

关于mysql - 如何从mysql中的单行中获取最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36094479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com