sql find match存在一种类型的记录,但另一种不存在

时间:2012-12-05 20:08:10

标签: sql join

我有以下(删节模式) - 3个表 - user,job,job_type

TABLE: job_type
COLUMN: job_type_id
1           
2

TABLE: user
COLUMN: user_id
101
102
103

TABLE: job
COLUMNS: job_id | user_id | job_type_id
              4 |     101 |           1
              5 |     101 |           2
              6 |     102 |           1
              7 |     103 |           2

我想编写一个查询,返回在job_type_id = 1的作业表中有作业的所有用户,但是如果他们还有job_type_id = 2的作业,则从结果中排除它们。因此,目标结果集应仅返回用户102。

3 个答案:

答案 0 :(得分:2)

select *
  from user u
 where exists (select * from job j
                where j.user_id=u.user_id
                  and j.job_type_id=1)
   and not exists (select * from job j
                    where j.user_id=u.user_id
                      and j.job_type_id=2)

答案 1 :(得分:1)

您尚未指出您正在使用的DBMS,但以下是一些几乎应该适用的查询:

SELECT DISTINCT user_id
  FROM job j1
 WHERE job_type_id = 1
   AND NOT EXISTS
        ( SELECT 1
            FROM job j2
           WHERE job_type_id = 2
             AND j2.user_id = j1.user_id
        )
;

SELECT DISTINCT user_id
  FROM job
 WHERE job_type_id = 1
   AND user_id NOT IN
        ( SELECT DISTINCT user_id
            FROM job
           WHERE job_type_id = 2
        )
;

SELECT DISTINCT j1.user_id
  FROM job j1
  LEFT
 OUTER
  JOIN job j2
    ON j1.user_id = j2.user_id
   AND j1.job_type_id = 1
   AND j2.job_type_id = 2
 WHERE j2.user_id IS NULL
;

某些DBMS还提供了可以使用的特殊MINUSEXCEPT功能。这看起来像这样:

SELECT user_id
  FROM job
 WHERE job_type_id = 1
MINUS                          -- or EXCEPT
SELECT user_id
  FROM job
 WHERE job_type_id = 2
;

答案 2 :(得分:0)

尝试:

Select * from
user U inner join Job J
on 
  J.user_id = U.user_id
inner join job_type T
on 
  T.job_type_id = 1
Where 
T.job_type_id <> 2