Obtenga datos de 3 tablas y muestre una buena tabla
Frecuentes
Visto 108 veces
0
I have 3 tables: users, rooms, room_access. in users is: user1, user2, user3 in rooms: room1 room2 roomN (i have about 10 rooms) room_access (room,uid): room1, 1; room2,1; roomN,1; room2,3; room1,3;
So. User3 have access to room1, user2 have access to roome, etc.
In admin area i want to display that:
Basically table rooms content is displayed table header and table users content is displayed table rows. Maybe there is way that i can select all that data in single query? And where is check symbol, there i want to place checkboxes. So. I don't know how to made that table.
1 Respuestas
2
Essentially you are trying to return the data via a PIVOT
. MySQL does not have a PIVOT
function so you can use a combination of aggregate functions and a CASE
statement. If you know ahead of time the number of rooms that you will have you can use:
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
ver Violín SQL con demostración
But if you have an unknown number of rooms then you can use a prepared statement to create a dynamic version
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;
ver Violín SQL con demostración
Respondido 28 ago 12, 14:08
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas mysql sql pivot or haz tu propia pregunta.
Please demonstrate what you have tried already - show us a mysql query you have tried, and some (html?) markup you have already got. Please see Cómo preguntar una buena pregunta - DaveP
i tried nothing. because i am thinking how to get data from database. I would be happy if it was one query. Drawing table in browser not problem. Problem is - how to get data from database ... - Guntis
posible duplicado de Mesa Pivote Con 3 Mesas - RichardTheKiwi