简体   繁体   中英

I want to select all users from table (users) where user does not have a pageId = 9 in table page_members

I am trying to select using join query, but I am failing, this is how my tables look enter image description here

my query

select *
from users u
left join page_members p on p.userId != u.id and p.pageId = 9;

But I am getting all users.

Check if this is what you want

  SELECT *
   FROM users u
   LEFT JOIN page_members p ON p.userId = u.id 
        AND p.pageId <> 9;

Simple <> or != (they are parsed as the same operator) would only remove the information about pageID assignement. So this is not the way.

If you are only interested in users, simple

SELECT * 
FROM users 
WHERE userID not IN 
      (SELECT userID FROM page_members WHERE pageID=9)

will suffice.

But if you need combined info from both tables, you have to either use the above subquery in a WHERE clause additionally to your JOIN, or use MINUS operator (but then you will end up with a spaghetti-query)

Choosing between LEFT or INNER join does not matter in this particular case. So in your case the sollution would be sth like:

SELECT * 
FROM users u 
  JOIN page_members p ON (p.userId = u.userId)
WHERE u.userID NOT IN 
    (SELECT userID FROM page_members WHERE pageID=9)

You are very close. Fix the left join and add where clause:

select *
from users u left join
     page_members p
     on p.userId = u.id and p.pageId = 9
where p.userId is null;   -- no match found

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