mysqlsqlvoting-system

voting system, relational db, sql query


I want to design voting system with two tables.

First table contains candidates' index and name.

The other one contains index, voter and candidate's index whom the voter support.

One voter can support multiple candidates.

I want a sql query that shows candidates' name with number of its supporters.

So the result looks like

John 12, Bob 8, David 3...

SELECT `name`, COUNT(table2.voter) AS `count` 
FROM `table1` 
LEFT JOIN `table2` 
   ON table1.idx = table2.support 
ORDER BY COUNT(table2.voter) DESC;

The above query gave only one row with total number of voter.

Can anyone give me any hints?


Solution

  • SELECT `name`, COUNT(table2.voter) AS `count` 
    FROM `table1` 
    LEFT JOIN `table2` ON table1.idx = table2.support
    GROUP BY `name`
    ORDER BY COUNT(table2.voter) DESC;
    

    You were missing a group by and hence getting only the first result.