0

I have 2 tables "browsers" and "votes". I need all the browsers and only the votes by a vote_ranking and a user_id. Sometimes there is no votes but i still need the browsers. That's the code i wrote:

SELECT browsers.*, votes.*
FROM browsers LEFT JOIN votes ON browsers.app_id = votes.app_id
WHERE vote_ranking = '$ranking' AND user_id = $userid or vote_id IS NULL

The problem is when there is no votes (vote_id IS NULL) the app_id is changed to NULL. But i need to keep the browsers app_id even there's no app_id in votes.

Can i join the table votes only on rows where the're is a vote_id ? Or anything similar to do what i need ?

Thanks

1 Answer 1

1

Try this:

SELECT browsers.*, votes.vote_ranking, votes.user_id
FROM browsers
LEFT JOIN votes
  ON browsers.app_id = votes.app_id
  AND vote_ranking = '$ranking' 
  AND user_id = $userid

This way, a corresponding record from votes will be joined only if it has appropriate vote_ranking. Otherwise there will be NULLs, but you will still keep the data from browsers.

Sign up to request clarification or add additional context in comments.

6 Comments

It does not keep the browsers data when there's no vote with a matching app_id, the browser row don't show up. vote_ranking is only in the votes table. The only matching data is app_id.
Have you tried my query? I definitely think it should work for you.
Yes i did and it only show the browsers with votes. The problem is in your WHERE it only show the rows with a user_id but when there is no vote, there is no user_id so the browser don't show up.
Ah. I didn't realize user_id was in the votes table. I'll fix the query now. Try it again.
Yes it's better but the id is still overwriting to null. Maybe the problem is in later. I mysql_fetch_assoc and when i use the $row["app_id"] it's blank. But i work with only the browser table it's not a code error it's the join that overwrite the app_id.
|

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.