电影院连续的空余座位的判断案例

编写一个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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值