一个表中的sql多条件

时间:2015-02-16 23:12:46

标签: mysql join

得到这样的表

+---------+------------+----------+
| user_id | project_id | group_id |
+---------+------------+----------+
|       1 |          1 |        1 |
|       1 |         10 |        1 |
|       2 |          2 |        1 |
|       2 |          3 |        1 |
|       3 |          3 |        2 |
+---------+------------+----------+

从group_id = 1中查找那些user_id,但不在project_id = 2中。在这种情况下,期望的输出将是

+---------+
| user_id |
+---------+
|       1 |
+---------+

我的问题

SELECT user_id
FROM STATUS
WHERE group_id = 1 and user_id NOT IN (
    SELECT user_id
    FROM STATUS
    WHERE project_id = 2
    GROUP BY user_id)
GROUP BY user_id

是子查询具有~1 000 000行,这使得整个查询非常慢(实际上> 5秒)。 它会是这个聪明的加入,还是选择2个?谢谢你的提示。

1 个答案:

答案 0 :(得分:0)

使用MINUS时mysql中joins的另一种替代方法,使用如下的连接:

select s1.user_id from (SELECT user_id,project_id,group_id
FROM STATUS 
WHERE group_id = 1) s1
join 
(SELECT user_id,project_id,group_id
FROM STATUS 
WHERE project_id = 2) s2 on s1.user_id <> s2.user_id