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

Posted 今天GaGa打代码了吗?

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 

以上是关于[LeetCode]603. 连续空余座位(Mysql自连接)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(数据库)- 连续空余座位

Mysql练习 连续空余座位 笛卡尔积

Mysql练习 连续空余座位 笛卡尔积

LeetCode-765 情侣牵手/交换座位

LeetCode:Database 06.换座位

Leetcode——链表和数组