Select*fromStudents;+----+-----------+-------- - -----------+----------------+|id|Nama |Negara |Bahasa|Kursus |+----+- - ---------+---------"/> Select*fromStudents;+----+-----------+-------- - -----------+----------------+|id|Nama |Negara |Bahasa|Kursus |+----+- - ---------+---------">

Rumah >pangkalan data >tutorial mysql >Bagaimana untuk menggunakan data lajur dalam pernyataan MySQL CASE?

Bagaimana untuk menggunakan data lajur dalam pernyataan MySQL CASE?

PHPz
PHPzke hadapan
2023-09-11 16:05:13883semak imbas

如何在 MySQL CASE 语句中使用列数据?

Untuk memahaminya, pertimbangkan data dalam jadual "Pelajar" seperti yang ditunjukkan di bawah -

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      |
| 9  | Harry     | NZ        | English  | Electronics    |
+----+-----------+-----------+----------+----------------+
9 rows in set (0.00 sec)

Sekarang, andaikan kita ingin tahu berapa ramai pelajar milik USA, UK, New Zealand, India, Russia, Perancis dll maka Kita boleh menggunakan lajur Negara dalam kenyataan KES seperti yang ditunjukkan di bawah -

mysql> Select SUM(CASE WHEN country = 'USA' THEN 1 ELSE 0 END) AS USA,
-> SUM(CASE WHEN country = 'UK' THEN 1 ELSE 0 END) AS UK,
-> SUM(CASE WHEN country = 'INDIA' THEN 1 ELSE 0 END) AS INDIA,
-> SUM(CASE WHEN country = 'Russia' THEN 1 ELSE 0 END) AS Russia,
-> SUM(CASE WHEN country = 'France' THEN 1 ELSE 0 END) AS France,
-> SUM(CASE WHEN country = 'NZ' THEN 1 ELSE 0 END) AS NZ,
-> SUM(CASE WHEN country = 'Australia' THEN 1 ELSE 0 END) AS Australia
-> From Students;
+------+------+-------+--------+--------+------+-----------+
| USA  | UK   | INDIA | Russia | France | NZ   | Australia |
+------+------+-------+--------+--------+------+-----------+
| 2    | 1    | 2     | 1      | 1      | 1    | 1         |
+------+------+-------+--------+--------+------+-----------+
1 row in set (0.07 sec)

Atas ialah kandungan terperinci Bagaimana untuk menggunakan data lajur dalam pernyataan MySQL CASE?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:tutorialspoint.com. Jika ada pelanggaran, sila hubungi admin@php.cn Padam