0

我正在尝试创建一个查询,其中包含以下条件下的表中的记录:

包括:

  1. 用户在作业表中有记录。
  2. 用户在作业表中有 NULL join_date 或记录

排除

  1. 用户在作业表中没有记录且非空 join_date

这是我的架构:

user --> user_id, join_date
job  --> job_id, user_id

user rows
user_id: 1, join_date: 1/24/13
user_id: 2, join_date: 1/24/13
user_id: 3, join_date: NULL
user_id: 4, join_date: NULL

job rows
job_id: 101, user_id: 1
job_id: 102, user_id: 3

我想编写一个返回用户#1、#3 和#4 的查询。我有以下不返回用户 #4 的查询:

SELECT DISTINCT u.[user_id], u.join_date, uj.job_id
FROM [user] u  
LEFT JOIN job uj ON (u.user_id = uj.user_id OR u.join_date is null)              
WHERE uj.user_id = u.user_id
4

2 回答 2

2

我认为这最好inwhere子句中表达:

select *
from user u
where u.join_date is null or
      u.user_id in (select user_id from job)

如果您也想要工作信息,您可以将工作信息加入为:

select u.*, j.job_id
from user u left outer join
     job j
     on u.user_id = j.user_id
where u.join_date is null or j.user_id is not null

这将为每个用户返回多行,每个作业一个。您只需要distinct是否可以为单个作业多次列出用户。

或者,如果您愿意:

select *
from user u
where not (u.join_date is not null and
           u.user_id not in (select user_id from job)
          )

这符合您的排除逻辑。

顺便说一句,in实际上not in只是外连接的特例。

于 2013-01-24T15:44:48.983 回答
0

Sql 小提琴演示

SELECT u.[user_id], u.join_date, uj.job_id
FROM [user] u  
LEFT JOIN job uj ON (u.user_id = uj.user_id) 
WHERE uj.job_id is null OR NOT u.join_date is null
于 2013-01-24T15:48:30.723 回答