LEFT JOIN 包含一个表中的组列表和另一个表中的标志
首先,如果标题有点不对劲,请见谅。我将用一个例子来解释我的情况。
我有一个像这样的 Groups
表:
id name 1 admin 2 developer 3 reviewer 4 beta tester 5 contributor
然后我有一个像这样的 Permissions
表:
id user_id group_id 1 60 1 2 60 2 3 60 3
我想要做的是使用 JOIN 查询最终得到如下结果:
(perm.) name part of group admin 1 developer 1 reviewer 1 beta tester 0 contributor 0
即,如果某个用户 ID 的条目链接到某个组 ID,则该用户位于该组中,因此将 1
放入该列中。我用它来打印管理页面的复选框列表。
我的问题很简单:在 MySQL 中如何做到这一点?显然是某种 JOIN,但它们让我很困惑。感谢您的任何帮助。
詹姆斯
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
RIGHT JOIN
意味着右表的每一行都有一行(即Groups
)。如果左表中的相应行(即Permissions
)不存在,则使用null
值创建它。我希望我很清楚:)
Joe 提出的 LEFT JOIN 的答案也是完全正确的,但我认为如果您必须添加更多条件,这种方式更具可扩展性。
The
RIGHT JOIN
means you have a row for each row of the right table (ieGroups
). If the corresponding row in the left table (iePermissions
) don't exists, it is created withnull
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.