为此,您可以使用CASE WHEN语句。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> FirstName varchar(20), -> Score int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('John',46); mysql> insert into DemoTable values('John',78); mysql> insert into DemoTable values('John',69); mysql> insert into DemoTable values('Chris',78); mysql> insert into DemoTable values('Chris',89);
使用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)