2
I have a table that records user reviews in Forum responses in rating, where: 0 = Vote No; 1 = Positive vote; 3 = Vote Annulled
If I want to take all votes in response from a single user on a topic I do the following:
SELECT reply_id, rating
FROM `forum_ratings`
WHERE topic_id = '4' and user_id = '29'
I have another query that takes all votes and groups by answer id, which in this case is the reply_id field.
SELECT reply_id,
sum(rating = '1') as likes,
SUM(rating = '0') as unlikes
FROM `forum_ratings`
WHERE topic_id = '4'
GROUP BY reply_id
I would like to group and at the same time have user X vote in front of the result for each reply_id. If the user has not voted either positive or negative in a response, the number 3 is shown. Something like:
reply_id likes unlikes current_user
6 234 12 0
7 122 44 1
8 14 5 3
I used your example but the results were not correct.
– Marcus Vinicius
where the user id-1 note was 1 and user id-29’s, the result of the user note 29 was 3
– Marcus Vinicius
If he voted it should be 1 positive or 2 negative, what you proposed in the code is exactly what I want. After grouping have the notes of a single user in each reply_id.
– Marcus Vinicius
In your example, user 29 only has a rating record (3), so I assumed that for all answers should show 3.
– bruno
Yes, in this case you’re right, but when the situation changes, it doesn’t work. Like for example if he voted 1 or 2, it should show 1 or 2, but it’s showing 3.
– Marcus Vinicius
Forgetting the example above. Imagine that there are only two votes in reply_id = 4. user_id_1 voted 1 and user_id_2 voted 2. I want the result with user_id_1 votes, it would have to return "1", but returns 3
– Marcus Vinicius
I did the test with the first chi and it worked, I just had to change the paarte (bd.forum_ratings) to (forum_ratings); But until then everything right, I will test with more users here.
– Marcus Vinicius
The second alternative with MIN seems to give the same result and is more concise. But I do not have much possibility to test.
– bruno
I tested it here and everything ok, I will send it to the site kkk. Thank you very much Bruno, you are beast!
– Marcus Vinicius
There’s nothing to be thankful for. :)
– bruno
I’ll test with the second too, think she has better performance?
– Marcus Vinicius
I would say yes. Because it would represent only a direct query in the forum_ratings table. To be sure only seeing the execution plan. But if the table doesn’t have many records, you shouldn’t notice the difference.
– bruno