我有一张像这样的“住所”:
CREATE TABLE residence (nameRoom varchar(100), idRoom int primary key,guest int, price int);
INSERT INTO residence (nameRoom, idRoom,guest,price) VALUES
('camera 1', 1,2,200),
('camera 2', 2,2,200),
('camera 3', 3,3,300),
('camera 4', 4,2,400),
('camera 5', 5,4,200),
('camera 6', 6,6,500);
我正在寻找一个SQL,它会给我最优惠价格的房间。
答案 0 :(得分:0)
这是一个subset sum problem。您找不到简单的查询来解决它。问题是NP完全。
答案 1 :(得分:0)
这是一个想法......
SELECT CONCAT_WS(', ',r1.nameroom,r2.nameroom,r3.nameroom) rooms
, r1.price+COALESCE(r2.price,0)+COALESCE(r3.price,0) total_cost
, r1.guest+COALESCE(r2.guest,0)+COALESCE(r3.guest,0) guests
FROM residence r1
LEFT
JOIN residence r2
ON r2.idroom < r1.idroom
LEFT
JOIN residence r3
ON r3.idroom < r2.idroom
HAVING guests >= 5
ORDER
BY total_cost;
+------------------------------+------------+--------+
| rooms | total_cost | guests |
+------------------------------+------------+--------+
| camera 5, camera 1 | 400 | 6 |
| camera 3, camera 1 | 500 | 5 |
| camera 5, camera 2, camera 1 | 600 | 8 |
| camera 3, camera 2, camera 1 | 700 | 7 |
| camera 5, camera 3, camera 2 | 700 | 9 |
| camera 6, camera 1 | 700 | 8 |
| camera 5, camera 3, camera 1 | 700 | 9 |
| camera 5, camera 4, camera 1 | 800 | 8 |
| camera 4, camera 2, camera 1 | 800 | 6 |
| camera 5, camera 4, camera 2 | 800 | 8 |
| camera 5, camera 4, camera 3 | 900 | 9 |
| camera 6, camera 5, camera 1 | 900 | 12 |
| camera 4, camera 3, camera 2 | 900 | 7 |
| camera 6, camera 5, camera 2 | 900 | 12 |
| camera 6, camera 2, camera 1 | 900 | 10 |
| camera 4, camera 3, camera 1 | 900 | 7 |
| camera 6, camera 3, camera 2 | 1000 | 11 |
| camera 6, camera 5, camera 3 | 1000 | 13 |
| camera 6, camera 3, camera 1 | 1000 | 11 |
| camera 6, camera 4, camera 1 | 1100 | 10 |
| camera 6, camera 4, camera 2 | 1100 | 10 |
| camera 6, camera 5, camera 4 | 1100 | 12 |
| camera 6, camera 4, camera 3 | 1200 | 11 |
+------------------------------+------------+--------+
23 rows in set (0.00 sec)