LeetCode:Database 27.连续空余座位
Posted Xiao Miao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Database 27.连续空余座位相关的知识,希望对你有一定的参考价值。
要求:几个朋友来到电影院的售票处,准备预约连续空余座位,你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?
cinema表:
| seat_id | free |
|---------|------|
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
Result Table:
| seat_id |
|---------|
| 3 |
| 4 |
| 5 |
分析:
1.要求查询出连续的空位,所以需要查找的坐位首先是个空位,其次它的前一个坐位是空位,或者后一个坐位是空位即可满足要求
SQL语句:
#1.方法1
SELECT DISTINCT seat_id
FROM(
SELECT a.seat_id AS seat_id
FROM cinema a
JOIN cinema b
ON a.seat_id=b.seat_id-1
AND a.free=1 AND b.free=1
UNION ALL
SELECT b.seat_id AS seat_id
FROM cinema a
JOIN cinema b
ON a.seat_id=b.seat_id-1
AND a.free=1 AND b.free=1)c
ORDER BY seat_id ASC;
#2.方法2
SELECT seat_id FROM(
SELECT seat_id,free,lead(free,1,0) over(ORDER BY seat_id) AS f1,lag(free,1,0) over() AS f2
FROM
cinema)a
WHERE free=1
AND (f1=1 OR f2=1)
ORDER BY seat_id ASC;
以上是关于LeetCode:Database 27.连续空余座位的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode:Database 77.找到连续区间的开始和结束数字