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)
廣告