从具有空值和非空值的多个列中获取最大值?
mysqlmysqli database
为此,您可以使用 COALESCE()。对于最大值,请在 MySQL 中使用 GREATEST()。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Value1 int, -> Value2 int, -> Value3 int -> ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(NULL,80,76); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values(NULL,NULL,100); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(56,NULL,45); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(56,120,90); Query OK, 1 row affected (0.21 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------+--------+--------+ | Value1 | Value2 | Value3 | +--------+--------+--------+ | NULL | 80 | 76 | | NULL | NULL | 100 | | 56 | NULL | 45 | | 56 | 120 | 90 | +--------+--------+--------+ 4 rows in set (0.00 sec)
以下是从多个列中获取最大值的查询 −
mysql> select greatest(coalesce(Value1,0),coalesce(Value2,0),coalesce(Value3,0)) from DemoTable;
这将产生以下输出 −
+--------------------------------------------------------------------+ | greatest(coalesce(Value1,0),coalesce(Value2,0),coalesce(Value3,0)) | +--------------------------------------------------------------------+ | 80 | | 100 | | 56 | | 120 | +--------------------------------------------------------------------+ 4 rows in set (0.00 sec)