查找空座位问题

空座位:

一个餐厅1000个座位,用1000行,一行一个整数、一个字符(描述位置的地址)来存储数据。要求管理这个餐厅的座位,方便查找出空座位。并且按照起始和结束座位号分为几个片区。即空座位号的起始和结束分为多少个空座位片区。
解惑1:在座位号加上正负号,正号代表空座位,负号代表已经入座。
update id=-id where id= @id
要根据座位号查找出输入哪个片区时候,可以用绝对值差select ABS(id) from seat 。结束营业时候,重置座位号set  id=ABS(id) 。
该方法虽然简单,但是在一列中存在了2个属性,
解惑2: 再建立一个表,存放已入坐的,已入坐的在源表中删除对应表。
解惑3: 加入两列无用的行id为0和1001,座位标记界限。
 
create table seat (id int not null primary key,area char(1))
insert into seat values(100,'A')
SELECT * FROM seat
查找一片空座位中的最后一个空座位,
select id from seat  where (id+1) not in (select id from seat) and id<1001
找到一片空座位中的第一个位置:
select id from seat where (id-1) not in (select id from seat) and id>0
现在使用两个视图把
create view  first_seat(id)  as select id from seat where (id-1) not in (select id from seat) and id>0
create view last_seat(id) as select id from seat  where (id+1) not in (select id from seat) and id<1001
 
找出空座位片区:
select f1.id as start, l1.id as finish  from first_seat as f1, last_seat l1 where l1.id=(select min(l2.id) from last_seat l2 where f1.id<=l2.id)

 

posted @ 2018-04-21 11:40  vansky  阅读(424)  评论(0编辑  收藏  举报