2014-03-13 60 views
0

我的投票表看起来像在我的数据库中;我想计算特定ID的总和

ID  CandidateID 
1   205 
2   209 
3   203 
4   205 
5   205 
6   209 

代码:

<?php $votes_query=mysql_query("select * from votes where CandidateID='$id'"); 
$vote_count=mysql_num_rows($votes_query); 
echo $vote_count; 
?> 

上面的代码提供了像,CandidateID 205 =3 votesCandidateID 209=2 votes

哪些代码可以在表格中总结这些选票是象,candidateID 205 + CandidateID 209 = 3+2=5个别结果?

+1

使用'select sum(votes)from CandidateID ='$ id'' –

+0

(sum)(http://www.tutorialspoint.com/mysql/mysql-sum-function.htm) – Dexa

+0

如果您有多个candidate_id然后使用'in'子句...'从候选人ID($ id)' –

回答

1

让所有候选人的投票候选明智:

<?php 
    $rs = mysql_query("select CandidateID, count(*) as vote_count from votes group by CandidateID"); 
    while(mysql_fetch_array($rs)){ 
    $CandidateID = $rs['CandidateID']; 
    $vote_count = $rs['vote_count']; 

    echo $CandidateID . " " . $vote_count; 
    } 

?> 

至获取所有选定候选人的投票数量

<?php 
    $rs=mysql_fetch_array(mysql_query("select count(*) as vote_count from votes where CandidateID in ($id)")); // where look like as $id = "'205','209'"; 
    $vote_count=$rs['vote_count']; 
    echo $vote_count; 
?> 
0

您需要使用COUNT聚合函数:

select count(*) as count_votes 
    from votes 
    where CandidateID='$id'"); 

而且一定要使用更好的数据库方法比mysql功能。您应该至少使用mysqli函数,因为它们对SQL注入更强大。

1
select * from votes where CandidateID in (1,5,7); 
0

你可以使用下面的查询中的所有选票总和:

select count(*) count from votes; 

上面的查询可以给你票的总数。

如果你想从一个查询的个人计票,你可以用下面的查询:

select CandidateID, count(*) count from votes group by CandidateID;