简体   繁体   中英

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?

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

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

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