如何在 SELECT 語句中使用 MySQL IF() 函式?


透過將列名與條件一同作為 IF() 函式的第一個引數,即可在 SELECT 語句中使用 MySQL IF() 函式。為了理解這一點,請考慮來自表“Students”的以下資料。

mysql> Select * from Students;
+----+-----------+-----------+----------+----------------+
| id | Name      | Country   | Language | Course         |
+----+-----------+-----------+----------+----------------+
| 1  | Francis   | UK        | English  | Literature     |
| 2  | Rick      | USA       | English  | History        |
| 3  | Correy    | USA       | English  | Computers      |
| 4  | Shane     | France    | French   | Computers      |
| 5  | Validimir | Russia    | Russian  | Computers      |
| 6  | Steve     | Australia | English  | Geoinformatics |
| 7  | Rahul     | India     | Hindi    | Yoga           |
| 8 | Harshit | India | Hindi | Computers |
+----+-----------+-----------+----------+----------------+
8 rows in set (0.00 sec)

現在,藉助以下查詢,我們將使用嵌在 SELECT 語句中的 IF() 函式,獲取學生姓名和課程詳細資訊,如果學生學習英語,則寫“Eng_Language”,否則為“其他語言”。

mysql> Select Name, IF(Language = 'English', "Eng_Language", "Other Language") AS 'Native Language', Course from students;
+-----------+-----------------+----------------+
| Name      | Native Language | Course         |
+-----------+-----------------+----------------+
| Francis   | Eng_Language    | Literature     |
| Rick      | Eng_Language    | History        |
| Correy    | Eng_Language    | Computers      |
| Shane     | Other Language  | Computers      |
| Validimir | Other Language  | Computers      |
| Steve     | Eng_Language    | Geoinformatics |
| Rahul     | Other Language  | Yoga           |
| Harshit   | Other Language  | Computers      |
+-----------+-----------------+----------------+
8 rows in set (0.00 sec)

更新於: 10-Feb-2020

3K+ 瀏覽

開啟你的 職業

完成課程獲得認證

開始學習
Advertisement
© . All rights reserved.