问题描述
您有桌子座位,它描述了飞机上的座位。它包含以下列:
- seat_no-座位的唯一编号;
- 状态-的状态 位子(0表示空闲,1表示保留,2表示 购买);
- person_id-保留/购买的人的ID 此席位(如果相应状态为0,则为0)。
您还有表请求,其中包含以下列:
- request_id-请求的唯一ID;
- 请求-请求的描述(1表示保留,2表示购买);
- seat_no-该人想要预订/购买的座位号;
- person_id-想要预订/购买此座位的人的ID。
一个人可以预订/购买免费座位,也可以购买自己预订的座位。
任务是在执行给定的请求后返回桌子座位。
注意:请求是从最低的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
在请求表中又增加了一行,在该表中,我们对三个座位的请求超过一个。在这种情况下,我们将使用具有最小请求ID的行。 4 | 2 | 3 | 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,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,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;