高级SQL选择查询/动态列

问题描述 投票:1回答:3

我正在倾向于使用MySQL,但在更高级的查询中苦苦挣扎,所以我希望有人可以解决一些问题

我有以下数据库(我希望它格式正确)

table_visitors
visitor_id | visitor_name
   1       |       Joe
   2       |       Bob

table_rooms
room_id | room_name
    1   |  room 1
    2   |  room 2 
    3   |  room 3
    4   |  room 4

table_roomsvisitors (indicates which visitors can access which rooms)
visitor_id | room_id
    1      |    1
    1      |    2
    1      |    3
    2      |    1
    2      |    4 

我想列出(针对特定访问者)table_rooms中的每个项目以及是否允许所选访客访问每个房间

预期的结果应该是这样的:

query for Joe:
room_name | access
 room 1   | true
 room 2   | true
 room 3   | true
 room 4   | false

query for Bob:
room_name | access
 room 1   | true
 room 2   | false
 room 3   | false
 room 4   | true
mysql sql
3个回答
0
投票

您可以使用左连接和case语句来检查用户是否可以访问房间

select r.room_name, 
       case when rv.visitor_id is not null then true else false end access
from table_rooms r
left join table_roomsvisitors rv on r.room_id = rv.room_id
and rv.visitor_id = 1

demo

基于另外的连接条件,在table_roomsvisitors中没有找到关联的左连接将产生null,因为rv.visitor_id = 1将仅连接来自table_roomsvisitors的行,其中visitor_id为1,而对于其他行,它将返回null,因此在select部分中你可以检查not null rows并返回true,false表示null行


0
投票

你可以使用CROSS JOIN

select v.visitor_name, r.room_name, 
       (case when rv.visitor_id is null then 'false' else 'true' end) as access
from table_visitors v cross join 
     table_rooms r left join
     table_roomsvisitors  rv 
     on rv.visitor_id = v.visitor_id and rv.room_id = r.room_id
where v.visitor_name = 'Joe';

0
投票

加入了表格然后使用了一个真假案例。那么id就是基于你自己说了bob的查询和joe的查询

对于乔:

select tr.room_name, case when rv.visitor_id is not null then 'true' else 'false' end access from table_rooms tr
left join table_roomvisitors rv on tr.room_id = rv.room_id
where rv.visitor_id = 1

鲍勃:

select tr.room_name, case when rv.visitor_id is not null then 'true' else 'false' end access from table_rooms tr
left join table_roomvisitors rv on tr.room_id = rv.room_id
where rv.visitor_id = 2
© www.soinside.com 2019 - 2024. All rights reserved.