Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Hiển thị tất cả sản phẩm có giá cao nhất trong bảng MySQL

Để lấy tất cả các sản phẩm có giá trị lớn nhất (MAX) trong cột số, dùng subquery tìm MAX rồi so sánh trong WHERE chính.

Ví dụ minh họa

Tạo bảng sản phẩm:

mysql> create table DemoTable ( 
    ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    ProductName varchar(100), 
    ProductAmount int 
);

Chèn dữ liệu (Product-3 và Product-5 cùng giá cao nhất 75):

mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-1',60);
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-2',40);
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-3',75);
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-4',50);
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-5',75);

Hiển thị dữ liệu:

mysql> select * from DemoTable;

Kết quả:

+-----------+-------------+---------------+
| ProductId | ProductName | ProductAmount |
+-----------+-------------+---------------+
| 1         | Product-1   | 60            |
| 2         | Product-2   | 40            |
| 3         | Product-3   | 75            |
| 4         | Product-4   | 50            |
| 5         | Product-5   | 75            |
+-----------+-------------+---------------+

Truy vấn subquery lấy tất cả sản phẩm giá MAX

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

Kết quả (2 sản phẩm cùng giá cao nhất):

+-----------+-------------+---------------+
| ProductId | ProductName | ProductAmount |
+-----------+-------------+---------------+
| 3         | Product-3   | 75            |
| 5         | Product-5   | 75            |
+-----------+-------------+---------------+

Giải thích:

  • Subquery: SELECT MAX(ProductAmount) FROM DemoTable → trả về 75
  • Truy vấn chính: Lọc ProductAmount = 75 → trả về tất cả hàng có giá 75
  • Khác với ORDER BY ... LIMIT 1 chỉ trả về 1 hàng

Cách khác (MySQL 8.0+): Dùng window function RANK() OVER (ORDER BY ProductAmount DESC) rồi lọc WHERE rank = 1.