简体   繁体   中英

Join 3 tables and return whatever is not in the 2nd and 3rd

I have 3 tables (users, assignedtechnicians, assignedsupervisors)

在此处输入图像描述

technicianid and uspervisorid are foreign keys to user id stationid and regionid are foreign keys to some other tables

Essentialy users are assigned to posts that way what i want to do is output the users that are not assigned to a post, in this case:

在此处输入图像描述

I know that full outer join must be the way to go but i cant get it to work

I would just use two not exists conditions for this, one to search in each bridge table:

select u.*
from users
where
    not exists (select 1 from assignedtechnicians ast where ast.technicianid = u.id)
    and not exists (select 1 from assignedsupervisors ass where ass.supervisorid = u.id)

You are looking for LEFT JOIN so that you can join on non-existing posts (the ones that you are looking for)

SELECT users.*
FROM users
LEFT JOIN posts ON posts.user_id = users.id
WHERE posts.id IS NULL

posts.id IS NULL means user does not have any posts.

You can write your query to be like this:

SELECT * from users U where U.user_id NOT IN (SELECT technicianid FROM assignedtechnicians) AND U.user_id NOT IN (SELECT uspervisorid FROM assignedsupervisors);

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