首页 > 解决方案 > SQL如何根据另一个表中满足的条件显示列值

问题描述

你有桌子座位,它描述了飞机上的座位。它具有以下列:

您还有表 requests,其中包含以下列:

一个人可以预订/购买一个免费座位,也可以购买他们已经预订的座位。

任务是在执行给定请求后归还桌位。

注意:请求从最低的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

标签: mysqlsql

解决方案


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;

推荐阅读