为什么我们应该使用 MySQL CASE 语句?
mysqlmysqli database更新于 2025/5/16 8:44:17
对于固定数量的参数,请使用 MySQL CASE。
语法如下
SELECT *, CASE WHEN yourColumName1>yourColumName2 THEN 'yourMessage1' ELSE 'yourMessage2' END AS anyAliasName FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table CaseFunctionDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Value1 int, -> Value2 int -> ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录。
查询如下
mysql> insert into CaseFunctionDemo(Value1,Value2) values(10,20); Query OK, 1 row affected (0.21 sec) mysql> insert into CaseFunctionDemo(Value1,Value2) values(100,40); Query OK, 1 row affected (0.10 sec) mysql> insert into CaseFunctionDemo(Value1,Value2) values(0,20); Query OK, 1 row affected (0.15 sec) mysql> insert into CaseFunctionDemo(Value1,Value2) values(0,-50); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from CaseFunctionDemo;
以下是输出 −
+----+--------+--------+ | Id | Value1 | Value2 | +----+--------+--------+ | 1 | 10 | 20 | | 2 | 100 | 40 | | 3 | 0 | 20 | | 4 | 0 | -50 | +----+--------+--------+ 4 rows in set (0.00 sec)
这是 CASE 语句的查询
mysql> select*, case when Value1>Value2 then 'Value1 is Greater' else 'Value2 is Greater' end AS Comparision from CaseFunctionDemo;
以下是输出 −
+----+--------+--------+-------------------+ | Id | Value1 | Value2 | Comparision | +----+--------+--------+-------------------+ | 1 | 10 | 20 | Value2 is Greater | | 2 | 100 | 40 | Value1 is Greater | | 3 | 0 | 20 | Value2 is Greater | | 4 | 0 | -50 | Value1 is Greater | +----+--------+--------+-------------------+ 4 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

