本质上,您正在尝试通过PIVOT
. MySQL 没有PIVOT
函数,因此您可以使用聚合函数和CASE
语句的组合。如果您提前知道您将拥有的房间数量,您可以使用:
select u.uname,
max(case when r.rname = 'room 1' then 'y' else 'n' end) room1,
max(case when r.rname = 'room 2' then 'y' else 'n' end) room2,
max(case when r.rname = 'room 3' then 'y' else 'n' end) room3
from users u
left join room_access ra
on u.uid = ra.userid
left join rooms r
on ra.roomid = r.rid
group by u.uname
但是如果您有未知数量的房间,那么您可以使用准备好的语句来创建动态版本
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(CASE WHEN rname = ''',
rname,
''' THEN ''Y'' ELSE ''N'' END) AS ',
replace(rname, ' ', '')
)
) INTO @sql
FROM rooms;
SET @sql = CONCAT('SELECT u.uname, ', @sql, '
from users u
left join room_access ra
on u.uid = ra.userid
left join rooms r
on ra.roomid = r.rid
group by u.uname');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;