Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีดึงค่าที่ไม่ซ้ำกัน (Unique) ของคอลัมน์ใน MySQL ด้วย DISTINCT


ใช้ DISTINCT ในคำสั่ง SELECT เพื่อกำจัดแถวซ้ำในผลลัพธ์

ไวยากรณ์

SELECT DISTINCT Columns FROM Table_name WHERE conditions;

ตัวอย่าง

ตาราง tender มีข้อมูล:

mysql> Select * from tender;
+----------+--------------+--------------+-------+
| clientid | client_Fname | Client_Lname | value |
+----------+--------------+--------------+-------+
|      100 | Mohan        | Kumar        | 60000 |
|      101 | Sohan        | Singh        | 50000 |
|      101 | Somil        | Rattan       | 55000 |
|      103 | Gaurav       | Kumar        | 75000 |
|      103 | Rahul        | Singh        | 63000 |
+----------+--------------+--------------+-------+
5 rows in set (0.00 sec)

ดึงค่าไม่ซ้ำของ Client_Lname:

mysql> Select DISTINCT client_Lname from tender;
+--------------+
| client_Lname |
+--------------+
| Kumar        |
| Singh        |
| Rattan       |
+--------------+
3 rows in set (0.05 sec)

ดึงค่าไม่ซ้ำของ client_Fname:

mysql> Select DISTINCT client_Fname from tender;
+--------------+
| client_Fname |
+--------------+
| Mohan        |
| Sohan        |
| Somil        |
| Gaurav       |
| Rahul        |
+--------------+
5 rows in set (0.00 sec)