您有桌椅,它描述了飞机上的座位。它有以下列:
您还有表请求,其中包含以下列:
一个人可以预订/购买免费座位,也可以购买他们已预订的座位。
任务是在执行给定的请求后归还餐桌座位。
注意:请求是从最低的request_id开始申请的;保证表请求中所有的 Seat_no 值都出现在表席位中。
对于给定的桌子座位
seat_no |status|person_id
-------------------------
1 | 1 | 1
2 | 1 | 2
3 | 0 | 0
4 | 2 | 3
5 | 0 | 0
和请求表
request_id | request | seat_no | person_id
-------------------------------------------
1 | 1 | 3 | 4
2 | 2 | 2 | 5
3 | 2 | 1 | 1
所需的输出
seat_no | status | person_id
----------------------------
1 | 2 | 1
2 | 1 | 2
3 | 1 | 4
4 | 2 | 3
5 | 0 | 0
第一个请求已完成,因为 3 号座位有空。第二个请求被忽略,因为 2 号座位已被其他人预订。第三个请求已完成,因为1号座位已被此人预订,因此他们可以购买。
我实现解决方案的方法是将两个表席位和请求进行外部联接,然后使用条件来显示所需的结果,但此查询仅正确返回最后两行:
select seat_no,status,person_id from
(SELECT COALESCE(r.request_id,0) as request_id,s.seat_no,
case when s.person_id=r.person_id then r.request
when s.person_id=0 then COALESCE(r.request,s.status)
else s.status
end as status,
case when s.person_id=0 and r.person_id is not null then r.person_id
when s.person_id!=r.person_id then s.person_id
else s.person_id
end as person_id
from seats s
left outer join requests r on s.seat_no=r.seat_no ) t
group by request_id,t.seat_no,status,person_id
order by seat_no asc
SELECT s.seat_no,
If(s.person_id = 0 || s.person_id = r.person_id, coalesce(r.request, s.status), coalesce(s.status, r.request)) as status,
If(s.person_id = 0 || s.person_id = r.person_id, coalesce(r.person_id, s.person_id), coalesce(s.person_id, r.person_id)) as person_id from
seats s left join (SELECT a.*
FROM requests a
INNER JOIN
(SELECT seat_no,
MIN(request_id) as request_id
FROM requests
GROUP BY seat_no
) AS b
ON a.seat_no = b.seat_no
AND a.request_id = b.request_id)
as r on s.seat_no = r.seat_no order by s.seat_no;
CREATE PROCEDURE solution()
BEGIN
with cte as (
select request_id,
request,
seat_no,
person_id,
Rank() over (partition by seat_no order by request_id) as rank1
from requests
),
cte1 as (
select *
from cte
where rank1 = 1
)
select s.seat_no,
case
when s.status = 0 and r.request = 1 then r.request
when s.status = 1 and r.request = 2 and s.person_id = r.person_id then r.request
when s.status = 0 and r.request = 2 then r.request
else coalesce(s.status,0) end as status,
case
when s.status = 0 and r.request = 1 then r.person_id
when s.status = 1 and r.request = 2 and s.person_id = r.person_id then r.person_id
when s.status = 0 and r.request = 2 then r.person_id
else coalesce(s.person_id,0) end as person_id
from seats as s
left join cte1 as r
on s.seat_no = r.seat_no;
END