<p>Let's say we have these tables;</p>

<p>table user:<br>
- id<br>
- username<br>
- email</p>

<p>table user2group:<br>
- userid<br>
- groupid</p>

<p>table group:<br>
- id<br>
- groupname</p>

<p>How do I make one query that returns all users, and the groups they belong to (as an array in the resultset or something..)</p>

```
```
select u.id, u.username, u.email, g.groupid, g.groupname
from user u 
join user2group ug on u.userid=ug.userid
join group g on g.groupid=ug.groupid
order by u.userid
```
```
As you are looping through the result set, each time you see a new userid make a new user object (or whatever) and add the groups to it.