如何在MySQL中仅显示和为小于150的列值?按照降序排列结果
为此,可以使用子查询。我们首先创建一个表 −
mysql> create table DemoTable844( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Amount int ); Query OK, 0 rows affected (0.95 sec)
使用insert命令在表中插入一些记录 −
mysql> insert into DemoTable844(Amount) values(80); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable844(Amount) values(100); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable844(Amount) values(60); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable844(Amount) values(40); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable844(Amount) values(150); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable844(Amount) values(24); Query OK, 1 row affected (0.40 sec)
使用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) < 150 order by Id;
这将产生以下输出 −
+----+--------+ | Id | Amount | +----+--------+ | 3 | 60 | | 4 | 40 | | 6 | 24 | +----+--------+ 3 rows in set (0.26 sec)
广告