需要包含NOT IN的一些结果

时间:2014-09-24 11:43:20

标签: sql mysqli

我在这里有一个SQL小提琴http://sqlfiddle.com/#!2/c6222/1需要一些帮助。

我需要返回任何group_id,其中user_id在该group_id 中没有'GROUP'设置。我在SQL小提琴中的查询是切出13565,因为它在另一个group_id中有'GROUP'。

它必须简单,但我无法得到它。

CREATE table role(
  role_id int,
  role_type varchar(255),
  group_id int,
  user_id int
);

INSERT INTO role VALUES(71002,'Group',1465,8301);
INSERT INTO role VALUES(71000,'Training_admin',1465,7959);
INSERT INTO role VALUES(71003,'Training_admin',1465,8301);
INSERT INTO role VALUES(71001,'Training_User',1465,7959);
INSERT INTO role VALUES(71004,'Training_User',1465,8301);
INSERT INTO role VALUES(71005,'Training_User',1465,13541);
INSERT INTO role VALUES(493513,'Initial',6314,13565);
INSERT INTO role VALUES(493522,'Ongoing',6314,13565);
INSERT INTO role VALUES(493534,'Initial',3128,13565);
INSERT INTO role VALUES(493556,'Group',3128,13565);

select * from role 
where user_id not in (select role.user_id 
    from role
    where role.role_type = 'GROUP')

2 个答案:

答案 0 :(得分:0)

使用NOT EXISTS代替NOT IN,这允许使用多个谓词:

SELECT  *
FROM    Role AS r
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    role AS r2
            WHERE   r2.user_id = r.user_id
            AND     r2.group_id = r.group_id
            AND     r2.role_type = 'GROUP'
        );

话虽如此,MySQL performs better using LEFT JOIN/IS NULL over NOT EXISTS,所以你应该改写为:

SELECT  r.*
FROM    Role AS r
        LEFT JOIN role AS r2
            ON r2.user_id = r.user_id
            AND r2.group_id = r.group_id
            AND r2.role_type = 'GROUP'
WHERE   r2.role_id IS NULL;

答案 1 :(得分:0)

以下是您在没有子查询的情况下查找的查询(为了获得更好的性能):

SELECT *
FROM role R
LEFT OUTER JOIN role R2 ON R2.user_id = R.user_id
                          AND R2.role_type = 'GROUP'
WHERE R2.user_id IS NULL

希望这会对你有所帮助。