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

นับค่าที่ไม่ซ้ำ (Distinct Items) ใน Query เดียวด้วย COUNT(DISTINCT) ใน MySQL

ภาพรวม

ใช้ COUNT(DISTINCT column) เพื่อนับจำนวนค่าที่ไม่ซ้ำกัน (Unique Values) ในคอลัมน์นั้นๆ ภายใน Query เดียว

ตัวอย่างสมบูรณ์

1. สร้างตารางและข้อมูล (ลูกค้า ซื้อสินค้าซ้ำ)

CREATE TABLE DemoTable (
    CustomerId INT,
    CustomerName VARCHAR(20),
    ProductName VARCHAR(40)
);

INSERT INTO DemoTable VALUES (101, 'Chris', 'Product-1');
INSERT INTO DemoTable VALUES (102, 'David', 'Product-2');
INSERT INTO DemoTable VALUES (101, 'Chris', 'Product-1');  -- ซ้ำ
INSERT INTO DemoTable VALUES (101, 'Chris', 'Product-2');  -- ลูกค้าเดิม ซื้อสินค้าต่าง
INSERT INTO DemoTable VALUES (101, 'Chris', 'Product-1');  -- ซ้ำ

2. ข้อมูลทั้งหมด

SELECT * FROM DemoTable;
+------------+--------------+-------------+
| CustomerId | CustomerName | ProductName |
+------------+--------------+-------------+
| 101        | Chris        | Product-1   |
| 102        | David        | Product-2   |
| 101        | Chris        | Product-1   |
| 101        | Chris        | Product-2   |
| 101        | Chris        | Product-1   |
+------------+--------------+-------------+

3. นับสินค้าที่ไม่ซ้ำ ที่ลูกค้า 101 ซื้อ

SELECT COUNT(DISTINCT ProductName) 
FROM DemoTable 
WHERE CustomerId = 101;

4. ผลลัพธ์

+-----------------------------+
| COUNT(DISTINCT ProductName) |
+-----------------------------+
| 2                           |  -- Product-1, Product-2
+-----------------------------+

COUNT() vs COUNT(DISTINCT)

ฟังก์ชันนับอะไรตัวอย่างข้างต้น
COUNT(ProductName)ทุกแถว (รวมซ้ำ)5
COUNT(DISTINCT ProductName)ค่าที่ไม่ซ้ำ2
COUNT(*)ทุกแถว5

การประยุกต์ใช้หลายคอลัมน์ (Multi-column Distinct)

-- นับคู่ (Customer, Product) ที่ไม่ซ้ำ
SELECT COUNT(DISTINCT CustomerId, ProductName) FROM DemoTable;
-- ผลลัพธ์: 3 (Chris-Product1, David-Product2, Chris-Product2)

ใน SELECT หลายคอลัมน์ (Conditional Counting)

SELECT 
    CustomerId,
    COUNT(DISTINCT ProductName) AS UniqueProducts,
    COUNT(*) AS TotalOrders
FROM DemoTable
GROUP BY CustomerId;

ผลลัพธ์

+------------+----------------+-------------+
| CustomerId | UniqueProducts | TotalOrders |
+------------+----------------+-------------+
| 101        | 2              | 4           |
| 102        | 1              | 1           |
+------------+----------------+-------------+

ประสิทธิภาพ

  • ต้องมี Index บนคอลัมน์ที่ COUNT DISTINCT จะเร็วขึ้น
  • ตารางใหญ่มาก ควรใช้ Approximate: APPROX_COUNT_DISTINCT() (MySQL 8.0.13+)
  • APPROX_COUNT_DISTINCT(col) เร็วมาก ผลลัพธ์ประมาณการ ±1-2%

สรุป

ใช้ COUNT(DISTINCT column) นับค่าที่ไม่ซ้ำใน Query เดียว รองรับหลายคอลัมน์ได้ และมี APPROX_COUNT_DISTINCT() สำหรับ Big Data