CASE WHEN 子句中的表示式為何在 MySQL 查詢中不起作用?


要實現此目的,請在 MySQL 中正確使用 CASE WHEN 語句。讓我們看看如何操作。

讓我們建立一個表 −

mysql> create table demo58
−> (
−> id int not null auto_increment primary key,
−> first_name varchar(20),
−> last_name varchar(20)
−> );
Query OK, 0 rows affected (2.15 sec)

使用插入命令向表中插入一些記錄 −

mysql> insert into demo58(first_name,last_name) values('John','Doe');
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo58(first_name,last_name) values('David','Smith');
Query OK, 1 row affected (0.29 sec)

mysql> insert into demo58(first_name,last_name) values('John','Brown');
Query OK, 1 row affected (0.11 sec)

mysql> insert into demo58(first_name,last_name) values('David','Miller');
Query OK, 1 row affected (0.26 sec)

使用 select 語句顯示錶中的記錄 −

mysql> select *from demo58;

將生成以下輸出 −

+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
|  1 | John       | Doe       |
|  2 | David      | Smith     |
|  3 | John       | Brown     |
|  4 | David      | Miller    |
+----+------------+-----------+
4 rows in set (0.15 sec)

以下是 CASE WHEN 中表達式的查詢 −

mysql> select
−> (
−> case
−> when (first_name = "John") then 'Carol'
−> when (last_name ="Smith") then 'Doe'
−> end
−> ) RESULT
−> from demo58;

將生成以下輸出 −

+--------+
| RESULT |
+--------+
| Carol  |
| Doe    |
| Carol  |
| NULL   |
+--------+
4 rows in set (0.00 sec)

更新日期:2020 年 11 月 20 日

217 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告