MySQL 语句中的 IF ELSE 语句?
在 If-Else 语句中,条件将根据值评估为真或假。
让我们看一个示例。首先,我们将创建一个表。CREATE 命令用于创建表。
mysql> create table IfelseDemo - > ( - > id int, - > FirstName varchar(100) - > ); Query OK, 0 rows affected (0.46 sec)
使用 INSERT 命令插入记录。
mysql> insert into IfelseDemo values(1,'John'); Query OK, 1 row affected (0.13 sec) mysql> insert into IfelseDemo values(2,'Carol'); Query OK, 1 row affected (0.31 sec) mysql> insert into IfelseDemo values(3,'John'); Query OK, 1 row affected (0.11 sec) mysql> insert into IfelseDemo values(4,'Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into IfelseDemo values(5,'John'); Query OK, 1 row affected (0.11 sec)
显示所有记录。
mysql> select *from IfelseDemo;
以下是我们的输出。
+------+-----------+ | id | FirstName | +------+-----------+ | 1 | John | | 2 | Carol | | 3 | John | | 4 | Carol | | 5 | John | +------+-----------+ 5 rows in set (0.00 sec)
以下是使用 if-else 语句的查询。
mysql> SELECT id, FirstName, (case when (id = 2 and FirstName = 'Carol') - > then - > 'Welcome Carol' - > else - > 'You are not Carol with id 2' - >end)as Message from IfelseDemo;
以下是输出。
+------+-----------+-----------------------------+ | id | FirstName | Message | +------+-----------+-----------------------------+ | 1 | John | You are not Carol with id 2 | | 2 | Carol | Welcome Carol | | 3 | John | You are not Carol with id 2 | | 4 | Carol | You are not Carol with id 2 | | 5 | john | You are not Carol with id 2 | +------+-----------+-----------------------------+ 5 rows in set (0.00 sec)
广告