我正在尝试为餐馆预订系统整理查询。我们的想法是,如果没有足够大的桌子来参加派对大小,那么可以查看其他免费桌子,找到两张足够大的桌子,以便容纳派对大小。
理想情况下,我希望能够选择最少的表格,以便与派对的大小相匹配。
例如,如果有一个十二表的请求,我希望理想情况下找到两个表,而不是更多。
这是我尝试的查询,但它给出了一个空结果
select tbl_id, sum(max_seats) as sumseats from tbl_list
group by tbl_id having sumseats> 11
我已经添加了一个指向sql小提琴的链接来显示表结构
答案 0 :(得分:1)
尝试类似下面的内容(除了MySQL之外,你还需要PHP之类的东西):
代码:
$bookedTables = array();
while ($requiredCapacity > 0) {
$query = "SELECT * FROM (SELECT tbl_id, max_seats FROM tbl_list WHERE max_seats > $requiredCapacity)table1 ORDER BY table1.max_seats ASC";
$result = mysql_query($query);
if (count($result)!=0) {
array_push($bookedTables, $result[0]['tbl_id'];
$requiredCapacity = $requiredCapacity - $result[0]['max_seats'];
}
else {
$query = "SELECT * FROM (SELECT tbl_id, max_seats FROM tbl_list)table1 ORDER BY table1.max_seats DESC";
if (count($result)!=0) {
array_push($bookedTables, $result[0]['tbl_id'];
$requiredCapacity = $requiredCapacity - $result[0]['max_seats'];
}
else {
echo "No more tables left";
break;
}
}
}
答案 1 :(得分:0)
我不是在暗示这是一个明确的答案,但这是值得考虑的事情......
SELECT * FROM tables;
+----+------+
| id | size |
+----+------+
| 1 | 2 |
| 2 | 2 |
| 3 | 2 |
| 4 | 2 |
| 5 | 4 |
| 6 | 4 |
| 7 | 4 |
| 8 | 6 |
| 9 | 6 |
| 10 | 8 |
+----+------+
SELECT *
, x.size + y.size + z.size pax
FROM tables x
LEFT
JOIN (SELECT * FROM tables UNION SELECT 0,0) y
ON y.size < x.size OR (y.size = x.size AND y.id < x.id)
LEFT
JOIN (SELECT * FROM tables UNION SELECT -1,0) z
ON z.size < y.size OR (z.size = y.size AND z.id < y.id)
HAVING pax >= 12
ORDER
BY pax
, x.size DESC
, y.size DESC
, z.size DESC
LIMIT 1;
+----+------+------+------+------+------+------+
| id | size | id | size | id | size | pax |
+----+------+------+------+------+------+------+
| 10 | 8 | 7 | 4 | -1 | 0 | 12 |
+----+------+------+------+------+------+------+