用於將 ENUM('M', 'F') 選作“男”或“女”的 MySQL 查詢?


您可以使用 IF() 實現此目的。我們首先建立一個表。此處的其中一列具有 ENUM 型別

mysql> create table DemoTable
   (
   UserId int,
   UserName varchar(40),
   UserGender ENUM('M','F')
   );
Query OK, 0 rows affected (1.11 sec)

使用 insert 命令在表中插入記錄 −

mysql> insert into DemoTable values(1,'John','M');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(2,'Maria','F');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(3,'David','M');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(4,'Emma','F');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

這將生成以下輸出 −

+--------+----------+------------+
| UserId | UserName | UserGender |
+--------+----------+------------+
| 1      | John     | M          |
| 2      | Maria    | F          |
| 3      | David    | M          |
| 4      | Emma     | F          |
+--------+----------+------------+
4 rows in set (0.00 sec)

以下是將 ENUM('M', 'F') 選作 'Male' 或 'Female' 的查詢−

mysql> SELECT UserId,UserName,IF(UserGender='F','Female', 'Male') AS `UserGender` from DemoTable;

這將生成以下輸出−

+--------+----------+------------+
| UserId | UserName | UserGender |
+--------+----------+------------+
| 1      | John     | Male       |
| 2      | Maria    | Female     |
| 3      | David    | Male       |
| 4      | Emma     | Female     |
+--------+----------+------------+
4 rows in set (0.00 sec)

更新於: 30-07-2019

2.0 千+ 已檢視

開啟你的 職業

完成課程即可獲得認證

開始
廣告