顯示 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)

更新於: 2019 年 9 月 30 日

387 次瀏覽

開啟您的 事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.