I have these tables:
calls: rows [ 'created_at', 'user_id']
users: rows ['id', 'username']
And I need to get all user without calls from date: How can I get it? Or what way is better and why?
I know three ways:
first:
SELECT id
FROM users
WHERE id NOT IN (SELECT user_id FROM calls where calls.created_at >= date)
second(I think it is not right, but I am not sure):
SELECT id
FROM users
LEFT OUTER JOIN calls
ON calls.user_id = users.id
WHERE calls.created_at >= date AND calls.user_id ISNULL
last:
SELECT id
FROM users
WHERE id NOT IN (
SELECT user_id
FROM calls
INNER JOIN users AS call_users
ON call_users.id = users.id
WHERE calls.created_at >= date
DB: PostgreSQL
>=
is wrong, that'll be<
not<=
, the first query will also include users, that are not incalls
at all (or with a creation time of null), whereas the second will only select users (I just guess that's the target for all three as the second and third also miss aFROM
(the third even twice)), that are incalls
with a not null creation time matching the inequality.NOT IN
a little if there are users, that are incalls
but not inusers
but those won't be selected fromusers
in the outer query either, as they don't exist. And I guess you might be best of with aNOT EXISTS
after all.