I have 3 tables, ‘u’ ‘d’ ‘s’
‘u’ has
- userid
- divid
‘d’ has
- divid
- divname
‘s’ has
- sname
- primaryuserid
- secondaryuserid
Now what I’d like to do is display a table with rows of the following format
- userid, divname, sname
Plus figure out a way to decipher whether userid is a primary or secondary for this sname table.
I’m able to show userid and divname using a left join, but I don’t know how I would add a third table? To make it trickier, there can be more than 1 snames for each userid, up to ~20. Is there a way to display 0-20 snames depending on the userid, separated with commas?
What I have currently is just and u and d tables corresponding to each other.
SELECT
e.userid,
e.divid,
d.divname
FROM
e
LEFT JOIN d ON (e.divid = d.id)
ORDER BY e.userid
You’re looking for a couple of different things here. First of all, the “way to display 0-20 snames depending on the userid, separated with commas” can be done with MySQL’s
GROUP_CONCAT()function, so your query would look like this (no distinction between primary and secondary yet):Now, to be able to distinguish whether the user is primary or secondary, you have to get a little fancier. I’d probably do it with a union, like this:
This will give you two rows (one Primary, one Secondary) for each userid with comma-separated lists of the snames.