I have the following database. One user can write one or more posts. Votes is many-to-many.
A user writes a post. Anyone can vote for the post, and thus the vote is saved in the vote table.
I need to display all the posts on a page. On each post, the post’s author, post_votes, and the votes of the author need to be displayed.
My tables are:
Table: user
id | user_name
1 | John
2 | Sam
3 | Susan
Table: post
id | post_title | user_id
1 | Hello | 1
2 | Sunday | 1
3 | Monday | 2
4 | Sun | 1
5 | Sun | 3
Table: votes
id | post_id
1 | 1
2 | 1
3 | 3
4 | 2
5 | 3
6 | 1
I need the query to return the following resultset:
post_id | post_votes | user_id | user_votes
1 | 3 | 1 | 4
2 | 1 | 1 | 4
3 | 2 | 2 | 2
4 | NULL | 1 | 4
5 | NULL | 3 | NULL
I tried all sorts of combinations, but my brain just won’t work. Also, would be very thankful if there is a better way to design the database so that retrieving the above can be made easy.
This is a little complicated. In cases like this, you often want to calculate each aggregated column separately. In this case, use one subquery to get the number of posts and another to get the number of users.