0

I have 3 tables users(name, email), reviews(review, entity, user) and votes(vote, entity, user), I want to make a query which returns all the reviews given for a particular entity, and vote from votes table if the user have voted for that entity, else null should be there at the place of vote. The query I wrote is

select users.name as name, 
reviews.review as review, 
votes.vote as vote 
from 
users join reviews on users.email=reviews.user 
left join votes on users.email=votes.user 
where reviews.entity='entity_id'

But this query is resulting multiple rows for some reviews, I made it working using group by, by am unable to understand the behavior of left join,

1 Answer 1

1

You are not joining votes for any specific entity, try the following:

select users.name as name, 
reviews.review as review, 
votes.vote as vote 
from 
users join reviews on users.email=reviews.user 
left join votes on users.email=votes.user and reviews.entity = votes.entity
where reviews.entity='entity_id'
Sign up to request clarification or add additional context in comments.

2 Comments

Remember group by clause as OP says: "But this query is resulting multiple rows for some reviews, I made it working using group by..."
I would have to see the working version, but I doubt the results would be correct by adding a group by. The query would still be looking for reviews with the entity 'entity_id', but votes for any entity from the same user.

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.