1

I am attempting to return whether a user has favourited an item or not. I have the MySQL statement:

SELECT *,`user_choice`.fav FROM `items`
LEFT JOIN `user_choice` ON `user_choice`.item_id = `items`.item_id

This returns a full set of results, with user_choice.fav equal to 0, 1 or NULL

However, I would like to only show the user_choice.fav (whatever that value may be) for a given user, so I have added a WHERE statement for that user like so:

SELECT *,`user_choice`.fav FROM `items`
LEFT JOIN `user_choice` ON `user_choice`.item_id = `items`.item_id
WHERE `user_choice`.user_id=xx

When I add this WHERE statement, it filters out any results from the first statement where user_choice.fav is NULL (ie not 1 or 0). How can I get it to return values even when they are NULL

example data:

items

item_id | item_name

1,itemname

2,item2name

3,item3name

user_choice

user_id | item_id | fav

1,1,1

1,3,0

1
  • Your question would be much clearer if you added sample data and desired results. Commented Jun 21, 2014 at 14:34

1 Answer 1

4

0, 1 are not considered NULL values, so your WHERE statement is excluding them. You need to add another OR into your WHERE clause as follows:

SELECT *,`user_choice`.fav FROM `items`
LEFT JOIN `user_choice` ON `user_choice`.item_id = `items`.item_id
WHERE `user_choice`.user_id=xx OR `user_choice`.user_id IS NULL
Sign up to request clarification or add additional context in comments.

4 Comments

will this try and match with the user first, then default to null?
No, in your question you've asked how to return values even if they are NULL.
I am trying to return 0 or 1 where the user_id in user_choice is equal xx, but if the corresponding item and user do not exist in user_choice I would like to return NULL, where presently it is removing the row
Try a FULL OUTER JOIN, otherwise you'll need to post some data along with the question.

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.