MySQL 中是否存在包含 IF/ELSE 语句的 SELECT?
是的,MySQL 中可以使用包含 IF/ELSE 的 SELECT。
我们首先创建一个表 -
mysql> create table DemoTable721 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100), Marks int, CountryName varchar(100) ); Query OK, 0 rows affected (0.57 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Chris',56,'US'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Robert',78,'UK'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Mike',45,'AUS'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Carol',89,'ENG'); Query OK, 1 row affected (0.22 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable721;
这将产生以下输出 -
+----+-----------+-------+-------------+ | Id | FirstName | Marks | CountryName | +----+-----------+-------+-------------+ | 1 | Chris | 56 | US | | 2 | Robert | 78 | UK | | 3 | Mike | 45 | AUS | | 4 | Carol | 89 | ENG | +----+-----------+-------+-------------+ 4 rows in set (0.00 sec)
以下是 MySQL 中实现包含 IF/ELSE 语句的 SELECT 的查询 -
mysql> select FirstName,IF(Marks > 75,Marks,CountryName) from DemoTable721;
这将产生以下输出 -
+-----------+----------------------------------+ | FirstName | IF(Marks > 75,Marks,CountryName) | +-----------+----------------------------------+ | Chris | US | | Robert | 78 | | Mike | AUS | | Carol | 89 | +-----------+----------------------------------+ 4 rows in set (0.00 sec)
广告