MySQL 中 select 语句内的 case 语句?
为此,可以使用 CASE WHEN 语句。首先让我们创建一个表格 -
mysql> create table DemoTable -> ( -> FirstName varchar(20), -> Score int -> ); Query OK, 0 rows affected (0.63 sec)
使用 insert 命令在表格中插入一些记录 -
mysql> insert into DemoTable values('John',46); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('John',78); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('John',69); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris',78); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Chris',89); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表格中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-----------+-------+ | FirstName | Score | +-----------+-------+ | John | 46 | | John | 78 | | John | 69 | | Chris | 78 | | Chris | 89 | +-----------+-------+ 5 rows in set (0.00 sec)
以下是 select 语句中实现 case 语句的查询 -
mysql> select FirstName,max(case when Score=69 then 1 else 0 end ) as isExistsOrNot -> from DemoTable -> group by FirstName;
这将产生以下输出 -
+-----------+---------------+ | FirstName | isExistsOrNot | +-----------+---------------+ | John | 1 | | Chris | 0 | +-----------+---------------+ 2 rows in set (0.00 sec)
广告