Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to store member of group in mysql table

I am developing an android application where people will sign up and join groups. I have a separate MySQL table which stores details of the users and another table which stores details of groups. But I have problem relating users to groups.

The users table will have his user_id, name, password, email_id, address, etc. The group table will have the group_id, group_name and other details regarding the group.

I must be able to get

  1. all the users who are in a group
  2. all the groups which a user has joined

quickly and easily.

Note: Assume you have over a 100k users and over 1000 groups.

like image 846
Senthil Vidhiyakar Avatar asked Feb 24 '16 06:02

Senthil Vidhiyakar


People also ask

What is the best way to store an attribute of large string values in SQL?

We can use varchar(<maximum_limit>) . The maximum limit that we can pass is 65535 bytes. Note: This maximum length of a VARCHAR is shared among all columns except TEXT/BLOB columns and the character set used.

What is rollup in MySQL?

The ROLLUP in MySQL is a modifier used to produce the summary output, including extra rows that represent super-aggregate (higher-level) summary operations. It enables us to sum-up the output at multiple levels of analysis using a single query.

What is GROUP BY 1 in MySQL?

In above query GROUP BY 1 refers to the first column in select statement which is account_id . You also can specify in ORDER BY . Note : The number in ORDER BY and GROUP BY always start with 1 not with 0.


1 Answers

The idiomatic way of doing this would be to have an additional n:m mapping table, which just holds pairs of IDs - a user and a group he or she belongs to:

CREATE TABLE group_membership (
    user_id INT NOT NULL,
    group_id INT NOT NULL,
    PRIMARY KEY (user_id, group_id),
    CONSTRAINT FOREIGN KEY (user_id) REFERENCES users (id),
    CONSTRAINT FOREIGN KEY (group_id) REFERENCES groups (id)
)

And now, e.g., if you wish to query all the users from my_group, you could do so with a couple of joins:

SELECT u.*
FROM   users u
JOIN   group_membership gm ON u.id = gm.user_id
JOIN   groups g ON gm.group_id = g.id
WHERE  g.name = 'my_group'
like image 97
Mureinik Avatar answered Sep 28 '22 12:09

Mureinik