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

การดึงข้อมูลแถวที่มีค่าต่ำสุดและสูงสุดในคอลัมน์ MySQL

เพื่อหาแถวข้อมูลที่มีค่าต่ำสุดและสูงสุดในคอลัมน์ ใช้ MIN() และ MAX() ในเงื่อนไข WHERE

สร้างตารางตัวอย่าง

mysql> create table DemoTable ( 
    CustomerName varchar(20), 
    ProductAmount int ) ; 
Query OK, 0 rows affected (1.03 sec)

เพิ่มข้อมูลตัวอย่าง

mysql> insert into DemoTable values('Chris',3599); Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',7843); Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Mike',97474); Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('Bob',65884); Query OK, 1 row affected (0.19 sec)

แสดงข้อมูลทั้งหมด

mysql> select *from DemoTable;
+--------------+---------------+
| CustomerName | ProductAmount |
+--------------+---------------+
| Chris        |          3599 |
| David        |          7843 |
| Mike         |         97474 |
| Bob          |         65884 |
+--------------+---------------+
4 rows in set (0.00 sec)

คิวรี่หาแถวค่าต่ำสุดและสูงสุด

mysql> select *from DemoTable where ProductAmount=(select max(ProductAmount) from DemoTable) 
    or ProductAmount=(select min(ProductAmount) from DemoTable);

ผลลัพธ์:

+--------------+---------------+
| CustomerName | ProductAmount |
+--------------+---------------+
| Chris        |          3599 |
| Mike         |         97474 |
+--------------+---------------+
2 rows in set (0.00 sec)

วิธีทางเลือกที่มีประสิทธิภาพมากกว่า (MySQL 8.0+)

-- ใช้ Window Functions
WITH ranked AS (
    SELECT *, 
           ROW_NUMBER() OVER (ORDER BY ProductAmount ASC) as rn_asc,
           ROW_NUMBER() OVER (ORDER BY ProductAmount DESC) as rn_desc
    FROM DemoTable
)
SELECT * FROM ranked WHERE rn_asc = 1 OR rn_desc = 1;

หากต้องการแค่ค่า MIN/MAX (ไม่ต้องการแถวทั้งหมด)

SELECT MIN(ProductAmount) as min_val, MAX(ProductAmount) as max_val FROM DemoTable;

กรณีมีค่าซ้ำหลายแถว

คิวรี่ต้นฉบับจะคืนค่าทุกแถวที่มีค่าเท่ากับ MIN หรือ MAX หากต้องการแค่ 1 แถว ให้เพิ่ม LIMIT 1 ใน subquery