Mark Mark - 1 month ago 8
MySQL Question

Check value if exist only in first table and not in second table

I have two SQL tables "user" and "entries".

I want to check with only one query if the user exists in first Table "user" or not and if the user has maked an entry in table "Entries" or not.

I want to make something like rating system. Where user should exist in table "user" and has no Entries in Table "entries". Because every user can make only one entry.

Is it possible to do it with only one query, how can i do it?

I know only how can i do it with two queries

SELECT COUNT(*) amount FROM user


SELECT COUNT(*) quantity FROM entries WHERE user_id = $userID

Answer Source

You should use the "NOT EXISTS" operator:

WHERE id = $userID
AND NOT EXISTS (SELECT * FROM entries where user_id = $userID);

It will return a row only if the user exists in the table "user" and has no entries in the table "entries".