简体   繁体   English

从多个表中选择多个行

[英]Selecting multiple rows from multiple tables

I have the following table structure: 我具有以下表结构:

- table users -
user_id
user_name

- table groups -
group_id
group_name

- table group_members -
group_id
user_id

Let's also say I have this in the DB: 还要说我在数据库中有这个:

users:
1:administrator

groups:
1:administrators
2:superusers
3:normal users

group_members:
1:1 (user_id 1 is member of group_id 1)
1:2
1:3

Now, how do I go efficient with selecting all users, and with that, the groups they're member of? 现在,如何高效地选择所有用户,以及选择这些用户所属的组? Do I have to execute 3 queries selecting all rows from all 3 tables, and fetch it with arrays in PHP, or is there a more effecient way to achieve this? 我是否必须执行3个查询,从所有3个表中选择所有行,并使用PHP中的数组进行获取,还是有一种更有效的方法来实现这一点?

select u.*, g.group_name
from users u
inner join group_members gm on gm.user_id = u.user_id
inner join groups g on g.group_id = gm.group_id
where u.user_id = 123

This query should work if there are no null fields in group and group_members table 如果group和group_members表中没有空字段,则此查询应该有效

if there are null fields replace inner join with left join 如果字段为空,则将内部联接替换为左联接

select users.username, group.group_name
from users  
inner join group_members on group_members.user_id = users.user_id
inner join groups  on group.group_id = group_members.group_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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