简体   繁体   中英

How can I select rows that dont exist in a different table?

I have 3 tables:

stoffen

-------------------
| pot (PK) | naam | 
-------------------
| 1        | dust |
| 2        | iron |
| 3        | gold |
-------------------

stoftesten

-----------------------------------------------------------------------
| id (PK) | score | done | stofid (FK : pot) | userid (FK : username) |
-----------------------------------------------------------------------
| 1       | 75    | Ja   | 1                 | user01                 |
| 2       | 25    | Ja   | 2                 | user01                 |
| 3       | 85    | Ja   | 2                 | user02                 |
-----------------------------------------------------------------------

users

-------------------------------------------
| username (PK) | name | rol      | basis |
-------------------------------------------
| user01        | Ben  | geleider | VLB   |
| user02        | Tom  | geleider | GER   |
-------------------------------------------

These 3 tables are all used in this query:

SELECT * 
FROM stoffen 
INNER JOIN stoftesten ON stoffen.pot = stoftesten.stofid 
INNER JOIN users ON users.username = stoftesten.gebruikersid 
WHERE stoftesten.done = 'Ja' and users.username = '$pers->username' 
ORDER BY naam";

It makes a list of all the 'stoffen' which are linked to a 'stoftest'. user01 gets a list with dust and iron, and user02 a list with just iron.

I was wondering if there is a way to make a list of items not on this list, the non used items list. So I did this:

SELECT * 
FROM stoffen 
LEFT JOIN stoftesten ON stoffen.pot = stoftesten.stofid 
LEFT JOIN users ON users.username = stoftesten.gebruikersid
WHERE stoftesten.gedaan IS NULL
ORDER BY stoffen.naam;

This creates the list I wanted, at least, that's what I thought. When I log in to a different account, I get the same 'not on the list' list. This is understandable, because I didn't specify any users.

But I can't find a way to do this. The 'stoftesten' table connects 'stoffen' and 'users'. Is there any way to show only the 'stoffen' which are not on the list, but different for every user?

Use a cross join to generate all rows. Then use a LEFT JOIN to get the matches and filter out any rows that actually match:

select s.pot, u.username
from stoffen s cross join
     users u left join
     stoffentesten st
     on s.pot = st.stofid and u.username = st.gebruikersid
where st.stofid is 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