MySQL 如何在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)
现在,通过使用IF()函数在SELECT语句中,我们将获得“学生”的名称和课程详情,如果他们使用英语,则输入“Eng_Language”,否则为“Other 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)
阅读更多:MySQL 教程