博客
关于我
LeetCode:Database 27.连续空余座位
阅读量:680 次
发布时间:2019-03-17

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

对于从cinema表中查询连续空余座位的问题,可以采用以下两种方法:

方法一:使用JOIN和UNION

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    WHERE 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    WHERE a.free = 1 AND b.free = 1) cORDER BY seat_id ASC;

方法二:使用LEAD和LAG

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) aWHERE free = 1 AND (f1 = 1 OR f2 = 1)ORDER BY seat_id ASC;

结果说明

两种方法均能有效识别连续空余座位。方法一通过 ##[UNION ALL]## 联合两个子查询,分别匹配当前空位与前一个空位,以及当前空位与后一个空位。方法二则利用 SQL 窗口函数 ##[LEAD()## 和 ##[LAG()##] 来识别连续空位区域,能够更直观地展示空位分布情况。

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

你可能感兴趣的文章
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>