在MySQL中是否有带有IF / ELSE语句的SELECT之类的东西?
是的,在MySQL中可以使用IF/ELSE进行SELECT。
让我们首先创建一个表-
create table DemoTable721 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100), Marks int, CountryName varchar(100) );
使用插入命令在表中插入一些记录-
insert into DemoTable721(FirstName,Marks,CountryName) values('Chris',56,'US'); insert into DemoTable721(FirstName,Marks,CountryName) values('Robert',78,'UK'); insert into DemoTable721(FirstName,Marks,CountryName) values('Mike',45,'AUS'); insert into DemoTable721(FirstName,Marks,CountryName) values('Carol',89,'ENG');
使用select语句显示表中的所有记录-
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的查询-
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)