为此,您可以使用子查询。让我们首先创建一个表-mysql> create table DemoTable844(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Amount int
);
使用插入命令在表中插入一些记录-mysql> insert into DemoTable844(Amount) values(80);
mysql> insert into DemoTable844(Amount) values(100);
mysql> insert into DemoTable844(Amount) values(60);
mysql> insert into DemoTable844(Amount) values(40);
mysql> insert into DemoTable844(Amount) values(150);
mysql> insert into DemoTable844(Amount) values(24);
使用select语句显示表中的所有记录。以下是查询-mysql> select *from DemoTable844;
这将产生以下输出-+----+--------+
| Id | Amount |
+----+--------+
| 1 | 80 |
| 2 | 100 |
| 3 | 60 |
| 4 | 40 |
| 5 | 150 |
| 6 | 24 |
+----+--------+
6 rows in set (0.00 sec)
如何在MySQL中仅显示总和小于150的列值mysql> select *from DemoTable844 tbl
where (select sum(Amount) from DemoTable844 where Amount <= tbl.Amount order by Amount)
order by Id;
这将产生以下输出-+----+--------+
| Id | Amount |
+----+--------+
| 3 | 60 |
| 4 | 40 |
| 6 | 24 |
+----+--------+
3 rows in set (0.26 sec)