mysql - SQL如何根据另一个表中满足的条件显示列值
问题描述
你有桌子座位,它描述了飞机上的座位。它具有以下列:
- seat_no - 座位的唯一编号;
- status - 座位的状态(0 表示空闲,1 表示保留,2 表示已购买);
- person_id - 预订/购买此座位的人的 ID(如果相应状态为 0,则为 0)。
您还有表 requests,其中包含以下列:
- request_id - 请求的唯一 ID;
- request - 请求的描述(1 表示保留,2 表示购买);
- seat_no - 该人要预订/购买的座位号;
- person_id - 想要预订/购买此座位的人的 ID。
一个人可以预订/购买一个免费座位,也可以购买他们已经预订的座位。
任务是在执行给定请求后归还桌位。
注意:请求从最低的request_id开始申请;保证表 requests 中的所有 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,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;
推荐阅读
- javascript - 将 npm 模块与 ES6 和 npm/bundlers 的未来一起使用
- datetime - 如何在本机反应中将 yyyy-mm-dd hh:mm:ss 转换为 mm-dd-yyyy hh:mm am/pm
- php - url变量的htaccess重写规则作为父文件夹
- javascript - 无法获得 div 的偏移量
- amazon-web-services - 我应该在配置文件 (.ebextensions) 或保存的配置下放置弹性 beanstalk 选项吗?
- winapi - 带有 CComboBox 的 CheckDlgButton
- c# - 如何使用动态 ApiSecret 通过 IdentityServer 中间件保护 api
- php - Laravel 的 Blade 模板 @yield 和 @section 是如何工作的?
- amazon-dynamodb - DynamoDB 使用全局二级索引查询
- apache-spark - 加入后火花丢弃多个重复的列