题目难度
简单
题目描述
几个朋友来到电影院的售票处,准备预约连续空余座位。
你能利用表 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) AS seat_id
FROM cinema c1
LEFT JOIN cinema c2
ON ABS(c1.seat_id-c2.seat_id)=1
WHERE c1.free=1 AND c2.free=1
ORDER BY seat_id;
ABS(c1.seat_id-c2.seat_id)=1
这个条件放在where 中计算会比较慢
在自连接的时候就筛选出来,因为如果放在where之前自连接,会多除很多ABS(c1.seat_id-c2.seat_id)=1
条件以外的数据,整个表冗余,where筛选时每条数据都要计算,更耗时。