Search code examples
mysqlsqldatabaseposts

Tally votes using SQL and JOIN (is this possible?)


My question is similar to this one, which I've tried the solution to, but it wasn't exactly right for my scenario.

I have 2 tables: votes and posts. Here is a basic sketch:

`posts`
----+------------------------------------------------------------------------+
| ID | post_title                                                            |
+----+-----------------------------------------------------------------------+
|  1 | Hello world.                                                          |
|  2 | This is a post!                                                       |
|  3 | What is the meaning of life?                                          |
|  4 | Looking for a good time?                                              |
+----+-----------------------------------------------------------------------

`votes`
+----+---------+
| ID | post_id | 
+----+---------+
|  1 |     1   |  
|  2 |     1   | 
|  3 |     1   |  
|  4 |     3   | 
|  5 |     3   |  
|  6 |     4   |  
+----+---------+

Problem:

I want to know how many votes each post got, and display them so that the post with the highest vote is at the top.

     Post ID   Vote Count
   +---------+-----------+
   | 1       | 3         |
   | 3       | 2         |
   | 4       | 1         |
   | 2       | 0         |

What does the SQL query look like to achieve this goal?


Solution

  • select post_id, count(*)
    from votes
    group by post_id
    order by count(*) desc
    

    EDIT:

    select v.post_id, count(*)
    from votes v INNER JOIN posts p ON v.post_id = p.id
    group by v.post_id
    order by count(*) desc