Forget about HABTM, those academic things are a sort of garbage in real life application, though you might require to answer this question in the future (or maybe right now).
So let me clarify a bit, you have these tables
users group_users groups
----- ----------- ------
id user_id id
name group_id name
So basically what you want to do is to SELECT users and have their groups listed with them, am I right ?
So the right query would be
SELECT users.name, groups.name
FROM users
INNER JOIN groups_users ON users.id = group_users.user_id
INNER JOIN groups ON groups.id = group_users.group_id
This however will list ONLY the users who have a group, if you want to select also those who haven't, you should perform a left join instead of a inner join (the first one).
I can't think of a really straight way to obtain what you want since a database will always return a set of rows. You have two ways to achieve what you want
- Use MySQl's GROUP_CONCAT
- Implement your own way through PHP (which isn't a big deal)