MySQL查询顺序的行数是多少?

时间:2010-03-15 19:38:00

标签: php mysql database sorting

我有一个用于投票的mysql表。有idproject_idvote字段(如果投票选择了特定项目,则为1)。现在我想根据这些条目生成排名。有没有办法获得每个project_id的投票数,并通过单个mysql查询自动按项目的TRUE投票数排序?或者你知道php方式吗?

e.g。

ID | Project ID | Vote
-----------------------
1  | 2          | 1
2  | 2          | 1
3  | 1          | 1

==>

项目编号2有2个投票

项目编号1有1个投票

提前致谢!

4 个答案:

答案 0 :(得分:5)

SELECT 
   `project_id`, SUM(`vote`) AS vote_count 
FROM 
   `table_name` 
GROUP BY `project_id`
ORDER BY vote_count DESC
如果你以关联数组的形式获取,

对SUM进行别名将帮助你在php中找到该列

答案 1 :(得分:3)

Select project_id, Sum( vote ) project_vote
From votes
Group By project_id
Order By project_vote Desc

GROUP BY允许您获得每个project_id的投票总和,ORDER BY DESC将最高票数放在首位。

答案 2 :(得分:0)

使用GROUP BY

SELECT project_id, SUM(vote) as votes 
FROM table 
GROUP BY project_id 
ORDER BY votes DESC

答案 3 :(得分:0)

试试这个:

SELECT 
    ProjectID,SUM(Vote) 
    FROM YourTable 
    GROUP BY ProjectID 
    ORDER BY Sum(Vote) DESC