2014-03-13 63 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;