博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:Database 27.连续空余座位
阅读量:678 次
发布时间:2019-03-17

本文共 811 字,大约阅读时间需要 2 分钟。

要求:几个朋友来到电影院的售票处,准备预约连续空余座位,你能利用表 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.方法1SELECT DISTINCT seat_idFROM(SELECT a.seat_id AS seat_idFROM cinema aJOIN cinema bON a.seat_id=b.seat_id-1AND a.free=1 AND b.free=1UNION ALLSELECT b.seat_id AS seat_idFROM cinema aJOIN cinema bON a.seat_id=b.seat_id-1AND a.free=1 AND b.free=1)cORDER BY seat_id ASC;#2.方法2SELECT seat_id FROM(SELECT  seat_id,free,lead(free,1,0) over(ORDER BY seat_id) AS f1,lag(free,1,0) over() AS f2FROMcinema)aWHERE free=1AND (f1=1 OR f2=1)ORDER BY seat_id ASC;

转载地址:http://hrnhz.baihongyu.com/

你可能感兴趣的文章