Question

I have a groups, users, and users_groups table. The relationship between users and groups is many to many. Users can be allocated to multiple groups. I would like to run a query that gets a list of groups which are COMMON between user_id1 and user_id2.

I have constructed the following query, but it seems to crash the system and the mysql server (on xampp), and the page takes forever to load (i.e. does not load).

Why is this? There are around 6000 test users in the users table, 30 groups in the groups table and 70,000 users_groups entries. Is there a better way to structure this query?

    $user_id1 = $this->db->escape($user_id1);
    $user_id2 = $this->db->escape($user_id2);
    $sql = "SELECT $select_string FROM users_groups
                INNER JOIN groups ON groups.group_id = users_groups.ug_group_id
                WHERE ug_group_id IN (SELECT ug_group_id FROM users_groups WHERE ug_user_id = $user_id2)
                AND ug_user_id = $user_id1 LIMIT 10";

    $query = $this->db->query($sql);
Was it helpful?

Solution

Use GROUP BY...HAVING

Try this:

SELECT $select_string 
FROM users_groups ug 
INNER JOIN groups g ON g.group_id = ug.ug_group_id
WHERE ug.ug_user_id IN ($user_id1, $user_id2)
GROUP BY g.group_id HAVING COUNT(DISTINCT ug.ug_user_id) = 2
LIMIT 10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top