0

I have a database where users must have a username and on another table have an optional contact_name that is given to them by each user.

For example:

user A might call user B 'FOO'

but user C calls user B 'BAR'

and user D might not have given user B a contact_name

so it should return NULL.

The query below works in getting me all the usernames and contact_names even when NULL which is the desired result.

SELECT Login.username, PhoneNumber.phone, AddressBook.contact_name FROM Login
LEFT OUTER JOIN PhoneNumber ON Login.id = PhoneNumber.user_id
LEFT OUTER JOIN AddressBook ON PhoneNumber.phone = AddressBook.phone

However, I only want to return WHERE AddressBook.user_id = 67 which will return the usernames and contact_names that User A is associated with.

Currently when I add WHERE AddressBook.user_id = 67 it doesn't return any of the contact_names with NULL values which is expected but I need those rows with NULL and without NULL contact_names.

How do I go about this?

Thanks

2 Answers 2

3

How about adding AddressBook.user_id = 67 to the JOIN:

SELECT l.username, p.phone, a.contact_name 
FROM Login l
LEFT OUTER JOIN PhoneNumber p ON l.id = p.user_id
LEFT OUTER JOIN AddressBook a ON p.phone = a.phone AND a.user_id = 67
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT Login.username, PhoneNumber.phone, AddressBook.contact_name FROM Login
LEFT OUTER JOIN PhoneNumber ON Login.id = PhoneNumber.user_id
LEFT OUTER JOIN (SELECT contact_name, phone, user_id from AddressBook where user_ID = 67 order by 1,2,3)ON PhoneNumber.phone = AddressBook.phone

I think this would be sufficient. Make your second left join only return the rows with 67 as user id. but honestly without knowing your relationships, it's hard to tell.

Is phone number really the only field you can join on?

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.