2

I have the following SQL with a JOIN, if I run this, it ignores records that have NULL values in the group_id in the users table. Therefore, I get less results

SELECT u.user_id, u.email, g.group_name 
FROM users u 
JOIN groups g USING (group_id) 
WHERE u.year=2017

However, If I run it without the JOIN like this:

SELECT u.user_id, u.email 
FROM users u 
WHERE u.year=2017

Then it gives all the users I need. Some of the users do not have the group_id set as this is not a required field. Is there a way to JOIN the NULL values too? Do I nee to have a NULL value in the groups table? This would not be possible as my group_id field in the groups table is NOT NULL and PRIMARY KEY

2 Answers 2

6

You have to use LEFT JOIN:

SELECT u.user_id, u.email, g.group_name 
FROM users u 
LEFT JOIN groups g USING (group_id) 
WHERE u.year=2017
Sign up to request clarification or add additional context in comments.

Comments

1

Use left join if you want to get all users whether they have group_id or not

SELECT u.user_id, u.email, g.group_name 
FROM users u 
LEFT JOIN groups g USING (group_id) 
WHERE u.year=2017

or using your's version tweak on clause

SELECT u.user_id, u.email, g.group_name 
FROM users u 
JOIN groups g ON(u.group_id = g.group_id OR u.group_id IS NULL) 
WHERE u.year=2017

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.