I have a “group_names” table which stores user groups. Each group has a manager, which can be either an individual user, or be managed by another group. This is currently determined by group_names.mgr_type. An INT value of 1 means that it’s an individual user and a value of 2 means that it’s a group that manages it.
For example, the “General Users” group could be managed by the “IT Department” group or by “John Doe”. Unique ID fields on the users and group_names tables are “user_id” and “group_id”.
I want to take the logic out of PHP and just put it in the SQL query, but I’m running into problems here. I’m not sure if this is possible given the table layout or if I’m just incapable of following simple instructions provided in the documentation.
SELECT gn.group_id, gn.group_name, ... gn.mgr_id, CONCAT(usr.user_firstname,' ',usr.user_lastname) AS created_name, usr.user_id,
CASE gn.mgr_type
WHEN '1' THEN CONCAT(usr.user_firstname,' ',usr.user_lastname) WHERE usr.user_id=gn.mgr_id LIMIT 1
WHEN '2' THEN gn.group_name WHERE gn.group_id=gn.mgr_id LIMIT 1
END AS mgr_name
FROM group_names gn
LEFT JOIN users usr
ON gn.created_by=usr.user_id
ORDER BY group_name ASC;
I’ve tried different variations of IF and CASE, with and without parentheses, but keep getting the “invalid syntax” error.
...for the right syntax to use near 'WHERE usr.user_id=gn.mgr_id LIMIT 1) WHEN '2' THEN (gn.group_name WHERE gn' at line 3
Can I even select a different row from the same table (select the group_name from a different row based on the mgr_id=group_id), or should I add another table?
Any suggestions on an easier/more efficient way to do this?
Thanks!
Have you tried this since you already joined to those tables
You actually need 2 more left joins for that to work
Left join to the user table to get the manager name if it’s user or join to group_names table to retrieve the group name if it’s a group
You can restrict the JOINs further