SQL在三个表中的至少两个表中找到匹配 - 组合查询

时间:2012-10-02 21:28:40

标签: sql join

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

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]表的主键。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

左外连接将导致查询尝试连接到表,但不要求子表具有匹配的记录。如果它没有匹配的记录,则该表中的字段将为null。此查询应该满足您的需求。

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)