如果在MySQL语句中使用ELSE语句?
在If-Else语句中,根据值将条件评估为true或false。
让我们来看一个例子。首先,我们将创建一个表。CREATE命令用于创建表。
mysql> create table IfelseDemo - > ( - > id int, - > FirstName varchar(100) - > );
在INSERT命令的帮助下插入记录。
mysql> insert into IfelseDemo values(1,'John'); mysql> insert into IfelseDemo values(2,'Carol'); mysql> insert into IfelseDemo values(3,'John'); mysql> insert into IfelseDemo values(4,'Carol'); mysql> insert into IfelseDemo values(5,'John');
显示所有记录。
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)