Database schema pattern for grouping records

和自甴很熟 提交于 2019-12-13 06:27:45

问题


I'm looking for a design pattern to manage records in a relational database which belong together, e.g. grouping multiple contacts. The group itself does not need to be an entity. A group should have an unlimited count of members.

It should be possible to run a query to get other group members of a given record.

My idea is to manage it in one table:

GROUPINGS
  integer group
  integer member_id

primary_key (group, member_id)
foreign_key (member_id)

EDIT: Beware that group is not a foreign key. It's just a unique identifier. It should be increased for every member group which is built.

Here is an example content:

GROUPINGS group | member_id
          -----------------
              1 | 10
              1 | 11
              1 | 12
              2 | 20
              2 | 21
              3 | 10
              3 | 40

This example contains three groups: (10,11,12) and (20,21) and (10,40). You see that 10 is included in two groups.

To query the "neighbors" of member 10 we can use this SQL statement:

SELECT g2.member_id
FROM groupings g1
JOIN groupings g2 ON g1.group      = g2.group 
                 AND g1.member_id != g2.member_id
WHERE g1.member_id = 10

=> 11,12,40

What do you think? Perhaps this is a known pattern - are there links to find more about this?

EDIT: Renamed table "groups" to "groupings" and renamed attribute "group_id" to "group" to make it obvious that a record in this table is not a group - it's a link between a group and a member. Group is not an entity.


回答1:





回答2:


What you have outlined is a pretty standard solution, a relational table between two entities - Group and Member. I am sure there are alternatives, but this is the solution I would go with.




回答3:


Looks fine to me - is a normal solution to end at if a member can be part of multiple groups, which presumably they can.

The only suggestion I'd make is with your SQL query - I'd use a JOIN instead, but that's nothing to do with your schema:

SELECT g2.member_id
FROM groups g1
    INNER JOIN groups g2 ON g1.group_id = g2.group_id AND g1.member_id <> g2.member_id
WHERE g1.member_id = 10


来源:https://stackoverflow.com/questions/8302054/database-schema-pattern-for-grouping-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!