Dùng IF() trực tiếp trong danh sách cột SELECT với điều kiện trên cột bảng.
Dữ liệu: Bảng 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 | +----+-----------+-----------+----------+----------------+
Truy vấn: Phân loại ngôn ngữ
mysql> SELECT
Name,
IF(Language = 'English', 'Eng_Language', 'Other Language') AS 'Native Language',
Course
FROM students;
Kết quả
+-----------+-----------------+----------------+ | 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 | +-----------+-----------------+----------------+
Cột Native Language được tính động từ cột Language.