从 MySQL 列中提取包含最低数字的行?
为此,可使用聚合函数 MIN() 配合 GROUP BY。在此,我们将会显示 NumberOfProduct 中的最低 ID。我们首先创建一个表格 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, NumberOfProduct int ); Query OK, 0 rows affected (0.19 sec)
使用插入命令在表格中插入一些记录 -
mysql> insert into DemoTable(NumberOfProduct) values(40); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(NumberOfProduct) values(40); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable(NumberOfProduct) values(60); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(NumberOfProduct) values(60); Query OK, 1 row affected (0.06 sec)
使用 select 语句显示表格中的所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+----+-----------------+ | Id | NumberOfProduct | +----+-----------------+ | 1 | 40 | | 2 | 40 | | 3 | 60 | | 4 | 60 | +----+-----------------+ 4 rows in set (0.00 sec)
以下是拉取列中最低数值行的查询 -
mysql> select NumberOfProduct,MIN(Id) from DemoTable group by NumberOfProduct;
这将生成以下输出 -
+-----------------+---------+ | NumberOfProduct | MIN(Id) | +-----------------+---------+ | 40 | 1 | | 60 | 3 | +-----------------+---------+ 2 rows in set (0.00 sec)
广告