简体   繁体   中英

LEFT JOIN with list of groups from one table, and flag from another

First off, sorry if the title is a little off. I'll explain my situation using an example.

I have a Groups table like this:

id  name
1   admin
2   developer
3   reviewer
4   beta tester
5   contributor

I then have a Permissions table like so:

id   user_id  group_id
1    60       1
2    60       2
3    60       3

What I want to do is use a JOIN query to end up with a result like this:

(perm.) name   part of group
admin          1
developer      1
reviewer       1
beta tester    0
contributor    0

Ie If there is an entry for a certain user ID which links to a certain group ID, that user is in that group, so a 1 is put in the column. I'm using this to print out a list of checkboxes for an admin page.

My question is simply: how can this be done in MySQL? Obviously a JOIN of some kind, but they confuse the hell out of me. Thanks for any help.

James

SELECT g.Name,
       CASE WHEN p.group_id IS NOT NULL THEN 1 ELSE 0 END AS part_of_group
    FROM Groups g
        LEFT JOIN Permissions p
            ON g.id = p.group_id
                AND p.user_id  = 60
    ORDER BY part_of_group DESC, g.Name
SELECT
    Groups.name,
    Permissions.id is not null
FROM Permissions
RIGHT JOIN Groups ON Permissions.group_id = Groups.id 
WHERE Permissions.user_id = 60

The RIGHT JOIN means you have a row for each row of the right table (ie Groups ). If the corresponding row in the left table (ie Permissions ) don't exists, it is created with null for values.

I hope I'm clear :)

The answer with a LEFT JOIN proposed by Joe is also perfectly correct, but I think this way is more extensible if you have to add more conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM