数据库
首页 > 数据库> > [LeetCode]603. 连续空余座位(Mysql、自连接)

[LeetCode]603. 连续空余座位(Mysql、自连接)

作者:互联网

题目

几个朋友来到电影院的售票处,准备预约连续空余座位。

你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?

| seat_id | free |
|---------|------|
| 1       | 1    |
| 2       | 0    |
| 3       | 1    |
| 4       | 1    |
| 5       | 1    |
 

对于如上样例,你的查询语句应该返回如下结果。

 

| seat_id |
|---------|
| 3       |
| 4       |
| 5       |

题解

使用自连接。

代码

select distinct(c1.seat_id)
from cinema c1 
join cinema c2
on abs(c1.seat_id-c2.seat_id)=1
where c1.free=1 and c2.free =1
order by c1.seat_id 

标签:603,cinema,free,seat,Mysql,LeetCode,c1,id,c2
来源: https://www.cnblogs.com/coding-gaga/p/13111016.html