如何在 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)
廣告