MySQL 根據第三個欄位的值從兩個欄位中選擇一個欄位?


為此,請使用 IF()。我們首先建立一個表 -

mysql> create table DemoTable
   -> (
   -> PlayerName varchar(100),
   -> PlayerScore int,
   -> PlayerStatus varchar(100)
   -> );
Query OK, 0 rows affected (0.58 sec)

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

mysql> insert into DemoTable values('John',88,'BAD');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('Chris',78,'BAD');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('Robert',90,'BAD');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('David',80,'BAD');
Query OK, 1 row affected (0.23 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select *from DemoTable;

輸出

+------------+-------------+--------------+
| PlayerName | PlayerScore | PlayerStatus |
+------------+-------------+--------------+
| John       | 88          | BAD          |
| Chris      | 78          | BAD          |
| Robert     | 90          | BAD          |
| David      | 80          | BAD          |
+------------+-------------+--------------+
4 rows in set (0.00 sec)

以下是根據第三個欄位的值從兩個欄位中選擇一個欄位的查詢 -

mysql> select PlayerScore,if(PlayerScore > 80 , PlayerName ,PlayerStatus) AS Result from DemoTable;

輸出

+-------------+--------+
| PlayerScore | Result |
+-------------+--------+
|          88 | John   |
|          78 | BAD    |
|          90 | Robert |
|          80 | BAD    |
+-------------+--------+
4 rows in set (0.00 sec)

更新時間: 2019-7-30

54 次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

入門
廣告