这是一张电影院座位预订计划。
Seat No Status
1 Booked
2 Available
3 Available
4 Available
5 Available
6 Available
7 Booked
8 Available
9 Available
10 Available如果有人想订6张票,他将获得2到6号座位和8号座位,如果有人只想订5张票,他将获得2到6号座位。
如何使用SQL查询(或PHP代码)了解相邻座位是否超过了所请求的座位?
按顺序选择座位是我需要实现的主要目标。
发布于 2010-02-25 23:08:17
试试这个:
select seat, status
from seats
where seat >= (
select a.seat
from seats a
left join seats b on
a.seat < b.seat and
b.seat < a.seat + 4 and
b.status = 'Available'
where a.status = 'Available'
group by a.seat
having count(b.seat)+1 = 4
)
limit 4这被设置为选择四个连续的座位。将"4“的所有实例调整为所需的座位数,以获得您想要的。
发布于 2010-02-25 22:36:47
一次传球。把你的号码放在?的位置。在满足要求时提供第一个序列中的座位号,如果找不到任何序列,则返回NULL。
SET @FOUND = 0;
SET @SEAT_MATCHED = NULL;
SELECT
IF(@FOUND < ?,
@FOUND := IF(status == 'Booked', 0, @FROM + 1),
@SEAT_MATCHED := IFNULL(@SEAT_MATCHED, seat_no)
)
FROM seats
ORDER BY seat_no
SELECT @SEAT_MATCHED;更多阅读:Control Flow Functions,User Variables
NB!此方法仅适用于在分析的间隔中有很少记录的情况!
也许您可以将预订座位的位掩码存储在行中,作为一个整数。例如,对于16个座位的行,数字36884 (二进制1001000000010100)表示预订了第3、5、13和16个座位。这将减少MySQL负载。然后你可以像这样做代码:
<?php
header('Content-Type: text/plain');
// data you get from DB
$seats = bindec('1001000000010100');
$num_seats = 16;
// calculate consecutive free seats
$seats_info = array();
for ($i = 0; $i < $num_seats; $i++, $seats >>= 1) {
if ($seats & 1) {
if (isset($first)) {
$seats_info[$first] = $i - $first;
unset($first);
}
}
else {
if (!isset($first)) {
$first = $i;
}
}
}
// output sequences
var_export($seats_info);
?>这将输出以下内容:
array (
0 => 2,
3 => 1,
5 => 7,
13 => 2,
)0是第一个座位。
发布于 2010-02-25 22:49:23
最好将已预订/可用表示为二进制数(例如,1-空闲,0-预订)。如果这样做,您可以优雅地使用聚合函数:
select seat as n from seats where
$num_seats = (select sum(status) from seats
where seat between n and n + $num_seats - 1)https://stackoverflow.com/questions/2334535
复制相似问题