简体   繁体   中英

SQL find match in at least two of the three tables - combine queries

I have three separate queries that I'd like to combine into a single query if possible. The intent is to find users that exist in any two of the three tables. They must exist AT LEAST two of the three tables.

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   

I'd like to somehow combine these queries into one larger query so that I can an easier time writing dynamic code to handle this business case.

The structure of the tables shouldn't matter, other than knowing they all have a foreign key called user_id which is the primary key of the [user] table.

If you don't want to restructure, try a query like this:

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)

Left outer joins will cause the query to attempt to join on a table, but not require that child-table to have a matching record. If it doesn't have a matching record, the fields from that table would be null. This query should do what you need.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM