使用 WHEN 子句实现 CASE 语句来检查 MySQL 中记录是否存在
mysqlmysqli database更新于 2025/12/20 16:12:17
首先我们创建一个表 −
mysql> create table DemoTable ( UserId int, UserName varchar(100) ); Query OK, 0 rows affected (0.57 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(101,'Robert'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(102,'David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(103,'Mike'); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------+----------+ | UserId | UserName | +--------+----------+ | 100 | Chris | | 101 | Robert | | 102 | David | | 103 | Mike | +--------+----------+ 4 rows in set (0.00 sec)
以下是 CASE WHEN 的查询 −
mysql> select case
when exists(select * from DemoTable where UserId=102)
then 'Present'
else 'Not Present'
end as Result;
这将产生以下输出 −
+---------+ | Result | +---------+ | Present | +---------+ 1 row in set (0.02 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

