php - Need a complex sql query for a MySQL database -


I have the following databases: A user can write one or more posts Votes are 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 one page. Each post must display the post author, post_wot, and the author's vote.

My tables are:

  Table: User ID | User_name 1 | John 2 | Sam 3 Susan Tables: Post ID | Post_title | User_id 1 | Hello 1 2 | Sunday | 1 3 | Monday | 2 4 | Sun | 1 5 | Sun | Table 3: Vote ID | Post_ id 1 | 1 2 | 1 3 | 3 4 | 2 5 | 3 6 | 1   

I need a query to get the following results:

  post_id | Post_wots | User_id | User_votes 1 | 3 | 1 | 4 2 1 | 1 | 4 3 2 | 2 | 2 4 | Faucet 1 | 4 5 Faucet 3 | NULL   

I tried all kinds of combinations, but my brain would not just work. Also, if there is a better way of designing the database, then it will be very grateful so that the above recovery can be easily done.

This is a bit complicated In such cases, you often want to calculate each collected column separately Are there. In this case, use one and one subkey to get the number of posts and to get the number of other users.

  Select p.post_id, pv.post_votes, uv.user_id, UV. P Skip the outer exclusion (select v.post_id, (count as Vote V group post_votes by v.post_id) * pv on pv.pv.id left external attendee (select p.user_id, count (*) Vote in the form of user_votes can be included in the p.id = v.post_id group by p.user_id) p.user_id = uv.user_id     on UV

Comments