显示MySQL表中具有最高金额的所有产品及其详细信息?
使用MAX()和子查询。此处,使用MAX()来获取最大金额。首先创建一张表 −
mysql> create table DemoTable
(
ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ProductName varchar(100),
ProductAmount int
);
Query OK, 0 rows affected (0.53 sec)
SQL
使用insert命令向表中插入一些记录 −
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-1',60);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-2',40);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-3',75);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-4',50);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ProductName,ProductAmount) values('Product-5',75);
Query OK, 1 row affected (0.12 sec)
SQL
使用select语句从表中显示所有记录 −
mysql> select *from DemoTable;
SQL
这将生成以下输出 −
+-----------+-------------+---------------+
| ProductId | ProductName | ProductAmount |
+-----------+-------------+---------------+
| 1 | Product-1 | 60 |
| 2 | Product-2 | 40 |
| 3 | Product-3 | 75 |
| 4 | Product-4 | 50 |
| 5 | Product-5 | 75 |
+-----------+-------------+---------------+
5 rows in set (0.00 sec)
SQL
以下是查询,显示具有最高金额的所有产品 −
mysql> select *from DemoTable where ProductAmount=(select max(ProductAmount) from DemoTable);
SQL
这将生成以下输出 −
+-----------+-------------+---------------+
| ProductId | ProductName | ProductAmount |
+-----------+-------------+---------------+
| 3 | Product-3 | 75 |
| 5 | Product-5 | 75 |
+-----------+-------------+---------------+
2 rows in set (0.00 sec)
SQL
阅读更多:MySQL 教程