编写一个SQL,查询电影院所有 连续可用的座位,返回座位按 seat_id升序排序的结果表,测试用例的生成使得两个以上的座位连续可用
建表语句:
drop table Cinema;
Create table If Not Exists Cinema (
seat_id int primary key auto_increment,/*座位id*/
free bool /* 免费的意思 free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。*/
)engine=innodb default charset=utf8 comment '电影院座位';
Truncate table Cinema;
insert into Cinema (seat_id, free) values ('1', '1');
insert into Cinema (seat_id, free) values ('2', '0');
insert into Cinema (seat_id, free) values ('3', '1');
insert into Cinema (seat_id, free) values ('4', '1');
insert into Cinema (seat_id, free) values ('5', '1');
试题说明:
seat_id 字段是一个自增的整数,free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。 思路:自连接,条件是相邻且空闲的座位。 连续空的情况有:3邻4=>1:1空 4邻5=>1:1空 abs()是绝对值,abs(a.seat_id-b.seat_id)=1是绝对值差值是1=》代表两座位是邻居的=就是连续的意思 abs(a.seat_id-b.seat_id)=1是绝对值差值是2=》代表两座位是间隔的=就是空一个的意思 去除重复a,b的座位distinct都是1号座位,2号座位,3号座位。。。
解法如下:
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;