和子集查询

rur96b6h  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(419)
CREATE TABLE Test (id integer, name varchar(100), weight integer, turn integer);
INSERT INTO Test (id, name, weight, turn) VALUES (5, "George Washington", 250, 1);
INSERT INTO Test (id, name, weight, turn) VALUES (4, "Thomas Jefferson", 175, 5);
INSERT INTO Test (id, name, weight, turn) VALUES (3, "John Adams", 350, 2);
INSERT INTO Test (id, name, weight, turn) VALUES (6, "Thomas Jefferson", 400, 3);
INSERT INTO Test (id, name, weight, turn) VALUES (1, "James Elephant", 500, 6);
INSERT INTO Test (id, name, weight, turn) VALUES (2, "Will Johnliams", 200, 4);

查询应该返回一个表,其中正好包含一条记录“thomas jefferson”,因为前三个人将适合(按顺序:george washingthon、john adams、thomas jefferson)。它们的重量之和是250+350+400
问题是我必须查询在能容纳max<=1000人的电梯里,人能放在哪里。我怎样才能解决这个问题?

aij0ehis

aij0ehis1#

我们可以在这里使用一个相关子查询来检查由转弯顺序给出的人员总运行重量:

SELECT t1.*
FROM Test t1
WHERE (SELECT SUM(t2.weight) FROM Test t2 WHERE t2.turn <= t1.turn) <= 1000
ORDER BY t1.turn DESC
LIMIT 1;

注意:如果您希望所有匹配的人都在体重限制范围内,那么只需删除 LIMIT 来自上述查询的子句。

相关问题