我的表结构如下:
table: user
user_id | join_date
101 | '2012-4-13'
102 | '2012-6-4'
103 | NULL
104 | NULL
table: job
job_id | user_id
20 | 101
21 | 103我希望返回包含以下内容的单个用户记录结果集:
下面是user_id的结果集,我希望看到:
user_id
101 <-- has a job
103 <-- has a job
104 <-- never joined, AND also does not have a job我是否需要使用公共表表达式来完成这个任务,还是可以在子查询中这样做?
请注意,为了简洁起见,我遗漏了实际的细节。这不是内部连接的简单情况。
下面是我的每个查询,它们分别运行:
这是返回#1的适当结果的查询。
SELECT DISTINCT u.*
FROM [user] u, job uj
WHERE u.user_id = uj.user_id这是返回#2的适当结果的查询。
SELECT DISTINCT u.*
FROM [user] u
FULL JOIN job uj ON u.user_id = uj.user_id
WHERE u.join_date IS NULL AND uj.user_id IS NULL 发布于 2012-12-13 21:37:06
这应该可以做到:
select u.user_id from [user] u
left join job j on u.user_id = j.user_id
where j.job_id is not null or (j.job_id is null and u.join_date is null)编辑:这在逻辑上是相同的,而且“更简单”,但第一种方式“读”像问题陈述:
select u.user_id from [user] u
left join job j on u.user_id = j.user_id
where j.job_id is not null or u.join_date is null发布于 2012-12-13 21:31:02
要获得`101、103和104,请尝试:
select distinct u.user_id
from [user] u LEFT JOIN job j
on u.user_id = j.user_id
where (u.join_date is not null and j.job_id is not null)
or u.join_date is nullhttps://stackoverflow.com/questions/13868755
复制相似问题