I have 4 tables : one with events, one with those events’ attendants, and two others containing information about those attendants, might they be single persons or groups of persons. The design of the database seems fair, right ?
I then need to get the name of who is going to attend a particular event. I’ll then get the type of the event’s attendants, and its id using a regular join. But i also need attendants’ names, and its stored in two different tables depending on what type the attendant is.
Have a look at what i did :
SELECT
ep.type_attendant 'type',
ep.id_attendant 'id',
IF( ep.type_attendant = 'user', CONCAT( u.firstname, ' ', u.lastname ), g.name ) 'fullname'
FROM
events_attendants ep,
events e,
users u,
groups g
WHERE
ep.id_event = e.id AND
ep.id_attendant = IF( ep.type_attendant = 'user', u.id, g.id )
That works, but is not perfect since it returns duplicate rows for the table groups.
What i’d like to end up with is something like that : (except the one below doesn’t work)
SELECT
ep.type_attendant 'type',
ep.id_attendant 'id',
IF( ep.type_attendant = 'user', CONCAT( u.firstname, ' ', u.lastname ), g.name ) 'fullname'
FROM
events_attendants ep,
events e,
IF( ep.type_attendant = 'user', users u, groups g ) -- variable table
WHERE
ep.id_event = e.id AND
ep.id_attendant = IF( ep.type_attendant = 'user', u.id, g.id )
I could also run two queries, and merge their results with PHP, but i’m the kind of guy who likes to learn.
MySQL database btw. Thanks for your help!
1 Answer