0

如果可能,我想将三个单独的查询合并为一个查询。目的是查找存在于三个表中任意两个表中的用户。它们必须至少存在三个表中的两个。

user (user table)
user_job_ft_job (full time job)
user_job_own_venture (startup/own venture)
user_job_not_looking (not seeking employment)

-- not seeking and full time
SELECT * from user_job_not_looking ujnl, user_job_ft_job uj, [user] u  
WHERE 1=1
AND ujnl.user_id = u.user_id
AND uj.user_id = u.user_id    

-- own venture and full time   
SELECT * from user_job_own_venture ujov, user_job_ft_job uj, [user] u   
WHERE 1=1
AND ujov.user_id = u.user_id
AND uj.user_id = u.user_id 

-- own venture and not looking
SELECT * from user_job_own_venture ujov, user_job_not_looking ujnl, [user] u   
WHERE 1=1
AND ujov.user_id = u.user_id
AND ujnl.user_id = u.user_id   

我想以某种方式将这些查询组合成一个更大的查询,以便我可以更轻松地编写动态代码来处理这个业务案例。

表的结构无关紧要,除了知道它们都有一个名为 user_id 的外键,它是 [user] 表的主键。

4

2 回答 2

2

如果您不想重组,请尝试这样的查询:

SELECT
    *
FROM
    user
    FULL JOIN user_job_not_looking AS ujnl ON ujnl.user_id = user.user_id
    FULL JOIN user_job_own_venture AS ujov ON ujov.user_id = user.user_id
    FULL JOIN user_job_ft_job AS ujfj ON ujfj.user_id = user.user_id
WHERE
    (ujnl.user_id IS NOT NULL AND ujov.user_id IS NOT NULL) OR
    (ujnl.user_id IS NOT NULL AND ujfj.user_id IS NOT NULL) OR
    (ujov.user_id IS NOT NULL AND ujfj.user_id IS NOT NULL)
于 2012-10-02T21:41:45.787 回答
1

左外连接将导致查询尝试连接一个表,但不要求该子表具有匹配的记录。如果它没有匹配的记录,则该表中的字段将为空。这个查询应该做你需要的。

select * from [user] u
left outer join user_job_not_looking as ujnl on ujnl.user_id=u.user_id
left outer join user_job_own_venture as ujov on ujov.user_id=u.user_id
left outer join user_job_ft_job as uj on uj.user_id=user_id
where 
(ujnl.user_id is not null and ujov.user_id is not null) or
(ujnl.user_id is not null and uj.user_id is not null) or
(ujov.user_id is not null and uj.user_id is not null)
于 2012-10-02T21:32:57.880 回答