I’m having a hard time describing this and it’s very possible that I am making this more difficult than it should be…
Basically, I have a page filled with pins/posts and users can upvote or downvote them. In one query, I want to get a list of the pins, but also join two tables to see if the user has upvoted or downvoted them.
The table structures:
pins table
| id | title |
+------+-------------------+
1 Post 1
2 Post 2
3 Post 3
4 Post 4
user_upvotes table
| id | user_id | pin_id |
+------+-----------+----------+
1 1 2
2 2 1
3 2 3
4 2 1
user_downvotes table
| id | user_id | pin_id |
+------+-----------+----------+
1 2 2
2 1 1
3 1 3
4 1 1
Here’s the query I have tried, but ends up duplicating the pins on the page.
SELECT pins.id AS pin_id, title, user_upvotes.id AS upvote, user_downvotes.id AS downvote
FROM pins
LEFT JOIN user_upvotes ON user_upvotes.pin_id = pins.id AND user_upvotes.user_id = 2
LEFT JOIN user_downvotes ON user_downvotes.pin_id = pins.id AND user_downvotes.user_id = 2
This results in (notice that pin_id 1 is repeated twice):
| pin_id | title | upvote | downvote |
| 1 | Post 1 | (NULL) | 2 |
| 1 | Post 1 | (NULL) | 4 |
| 2 | Post 2 | 1 | (NULL) |
| 3 | Post 3 | (NULL) | 3 |
| 4 | Post 4 | (NULL) | (NULL) |
From this point I just check if the value is NULL and if not, I attach a css class to indicate that it has been upvoted or downvoted.
Essentially, I want the above results, just without the pin being duplicated. If you have a better way of doing this, feel free to let me know that as well.
Add GROUP BY