开发者

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

开发者 https://www.devze.com 2023-03-05 06:47 出处:网络
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:

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
contribut开发者_运维知识库or    0

I.e. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消