使用 CASE 语句和 WHEN 从句实现检查 MySQL 中是否存在记录
让我们首先创建一个表 -
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)
广告