幾個朋友來到電影院的售票處,準備預約連續空余座位。
你能利用表?cinema?,幫他們寫一個查詢語句,獲取所有空余座位,并將它們按照 seat_id 排序后返回嗎?
| seat_id | free |
|---------|------|
| 1 ? ? ? | 1 ? ?|
| 2 ? ? ? | 0 ? ?|
| 3 ? ? ? | 1 ? ?|
| 4 ? ? ? | 1 ? ?|
| 5 ? ? ? | 1 ? ?|
?
對于如上樣例,你的查詢語句應該返回如下結果。
?
| seat_id |
|---------|
| 3 ? ? ? |
| 4 ? ? ? |
| 5 ? ? ? |
注意:
seat_id 字段是一個自增的整數,free 字段是布爾類型('1' 表示空余, '0' 表示已被占據)。
連續空余座位的定義是大于等于 2 個連續空余的座位。
思路:自連接,條件是相鄰且空閑。
select distinct a.seat_id as 'seat_id'
from cinema as a,cinema as b
where a.free=1 and b.free=1 and abs(a.seat_id-b.seat_id)=1
order by a.seat_id;
?