如何在 SELECT 语句中使用 MySQL IF() 函数?
完全可以在 SELECT 语句中使用 MySQL IF() 函数,方法是将列名称和条件作为 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”,否则为“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)
广告