顯示 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)
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP