开发者

Creating a group of users in PHP and MySQL

I'm wonderin开发者_JAVA百科g how I can use JOIN or LEFT JOIN to group users.

users table:

id (primary)
user (varchar)
pass (varchar)
email (varchar)
website (varchar)
bio (text)
avatar (varchar)
code (varchar)
active (varchar)
admin (varchar)
group_1 (int) <--- I have a feeling that this is the wrong way to go about it
group_2 (int) <---
group_3 (int) <---

groups table:

group_id (primary key)
group_name (varchar)
group_bio (text)
group_website (varchar)

I was wondering how I could let a member be part of several groups and to show a list of members of a certain group..

Something like this:

Group Name
Users: <a href='profile'>Name</a>, <a href='profile'>Name</a>, <a href='profile'>Name</a>, <a href='profile'>Name</a>

I have absolutely no idea how to go about this. Please help.


You want a standard many-to-many relationship.

This is usually implemented by having three tables.

  1. Users
  2. Groups
  3. Memberships

The memberships table will have two foreign keys, which map on to the other two tables.


You have to create a new table MEMBER_GROUPS with two fields: user_id and group_id.
Every row is a membership of a user...
In this way you can easily query user membership in a group...


This is indeed the wrong approach, as it restricts a user to three group memberships. This is a classic many-to-many relationship, and you can model it using a bridge table:

user_group
----------
user_id
group_id

The primary key will be a composite of user_id and group_id, enforcing uniqueness. Then you would do a double-join through this table. For example, to get all of the members of all of the groups:

SELECT group.*, user.*
FROM group
LEFT OUTER JOIN user_group
ON group.group_id = user_group.group_id
LEFT OUTER JOIN user
ON user_group.user_id = user.user_id

Or, if you are after a specific group:

SELECT user.*
FROM user_group
INNER JOIN user
ON user_group.user_id = user.user_id
WHERE user_group.group_id = ?

You could even get a list of all groups, with membership count:

SELECT group.*, COUNT(user_group.user_id) AS group_membership_count
FROM group
LEFT OUTER JOIN user_group
ON user_group.group_id = group.group_id
GROUP BY group.group_id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜