显示 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)
使用 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)
使用 select 语句在表中显示所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+-----------+-------------+---------------+ | 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)
以下是显示所有最高金额商品的查询 -
mysql> select *from DemoTable where ProductAmount=(select max(ProductAmount) from DemoTable);
这将生成以下输出 -
+-----------+-------------+---------------+ | ProductId | ProductName | ProductAmount | +-----------+-------------+---------------+ | 3 | Product-3 | 75 | | 5 | Product-5 | 75 | +-----------+-------------+---------------+ 2 rows in set (0.00 sec)
广告