更高效的SQL查询结构

时间:2014-01-10 12:02:16

标签: mysql sql select group-by

我有一个groupsusersusers_groups表。用户和组之间的关系是多对多的。用户可以分配到多个组。我想运行一个查询,该查询会将 至少 1个公共组的用户列表添加到特定用户ID。

  1. 如何重新构建此查询以使其更快?我认为这可能与使用GROUP BY有关吗?

  2. 如何实现排序,以便首先显示具有更多常见组的用户?

    $user_id = $this->db->escape($user_id);
    $sql = "SELECT DISTINCT(ug_user_id) 
                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_id)
                LIMIT 50";
    $query = $this->db->query($sql);
    

2 个答案:

答案 0 :(得分:2)

加入桌子:

SELECT DISTINCT (g2.ug_user_id)
    FROM
        users_groups as g1
        JOIN
        users_groups as g2 
        ON g1.ug_group_id = g2.ug_group_id
            and g1.ug_user_id != g2.ug_user_id
    WHERE g1.ug_user_id = $user_id;

答案 1 :(得分:1)

此外,您可以使用以下查询来获取按公共组数量排序的列表:

SELECT ug_user_id, 
       COUNT(*) AS COMMONCOUNT
       FROM users_groups
       WHERE ug_group_id IN (
                    SELECT ug_group_id 
                    FROM users_groups 
                    WHERE ug_user_id = $user_id)
             AND ug_user_id <> $user_id
GROUP BY ug_user_id     
ORDER BY COMMONCOUNT DESC