Mysql query fetch all rows that matches the user groups 只有一个

Mysql query fetch all rows that matches the user groups is only one

我在 mysql 数据库中有两个 table

1.loc8_users (id,username,password,email,phone)

2.loc8_users_groups (id,user_id,group_id).

这里 loc8_users_groups 存储分配给每个用户的组 ID。

我想从 loc8_users table 中获取用户只有一个组的所有行

请试一试:

SELECT 
U.*
FROM loc8_users U
INNER JOIN 
(
    SELECT 
    UG.user_id
    FROM loc8_users_groups UG
    GROUP BY UG.user_id
    HAVING COUNT(DISTINCT UG.group_id) = 1
) AS t
ON U.id = t.user_id

解释:

SELECT 
 UG.user_id
FROM loc8_users_groups UG
GROUP BY UG.user_id
HAVING COUNT(DISTINCT UG.group_id) = 1;

此查询 returns 只查询那些 user_id 只涉及一个组的人。

我们得到了那些 user_ids 但现在我们需要那些 user_ids 的用户信息。因此,在匹配 user_id 时,在此查询结果和 loc8_users table 之间创建一个 INNER JOIN 就可以了。