php代码选择最大值并显示表中最大值的计数

时间:2014-10-09 10:55:08

标签: php mysql

表名选民 字段名称 - partyname,州,方向,候选名称,区,投票 表中的日期就像明智的

BJP Maharashtra Nagpur-East Nitin Gadkari   Nagpur  3000    
Congress    Maharashtra Nagpur-East Lucky   Nagpur  2500    
BJP Maharashtra Nagpur-South    Rakesh  Nagpur  12000   
Congress    Maharashtra Nagpur-South    Shyam   Nagpur  15000   

我从表格中选择最大投票,关于州,方向和地区的条件。 并在下面显示投票。

现在我想问你如何获得上面的查询结果并显示每个方向上我的表中最大值的数量。 PLZ建议我...... 我只需要显示最大值方向的计数。

for ex --- 方向投票方 东5000 bjp 东8000 aap 然后在东方向只有1个最大值然后显示计数1 .. 请告诉我....

<table class="bordered">
    <tr> 
    <?php           
        $sqlst = "SELECT DISTINCT state FROM voter_count";
        $resultst = mysql_query($sqlst);
        while($rowst = mysql_fetch_array($resultst,MYSQL_ASSOC))
        {
        ?>  
    <td> 
<table class="bordered">
    <thead>
    <tr>             
        <th colspan="3"><?php echo $rowst['state']; ?></th>
    </tr>

     <?php  
        $state = $rowst["state"];           
        $sqlco = "SELECT DISTINCT district,direction FROM voter_count where state = '$state'";          
        $resultco = mysql_query($sqlco);
        while($rowco = mysql_fetch_array($resultco,MYSQL_ASSOC))
        {
        ?>    
     <tr>   
         <?php      
        $district = $rowco['district'];         
        $direction = $rowco['direction'];       
        $sqlvotes = "SELECT  MAX(votes) AS Vote,direction FROM voter_count where state = '$state' AND district = '$district' AND direction = '$constituency'";              
        $resultvotes = mysql_query($sqlvotes);                      
        while($rowvotes = mysql_fetch_array($resultvotes,MYSQL_ASSOC))
        {               

        ?>   
         <th><?php echo $rowvotes['Vote']; ?></th>      
          <th><?php echo $rowvotes['direction']; ?></th>         
    </tr>
    <?php }  } ?>
    </thead>
    </table>
</td>
<?php } ?>
</tr>
</table>

2 个答案:

答案 0 :(得分:0)

不是100%确定你的决赛桌需要什么,但这是一个开始(你不需要你的第一个查询,你可以用一个查询做你想要的):

  SELECT  MAX(votes) AS Vote,direction, state, district FROM voter_count
  group by direction, state, district

如上所述,其中一条评论请参阅此链接,了解如何使用group by: http://www.w3schools.com/sql/sql_groupby.asp

答案 1 :(得分:0)

如果您使用单个表进行存储,我不太清楚您的情况。

我建议你

制作两个表一个用于id,state,direction,district

和另一个用于id,fkid(区域的id),partyname,候选名称,投票

这使您的工作更轻松

然后

 $con  =    db_connect();
 $str   =   "select a.state,a.direction,a.district
             from tabel1 as a 
             inner join tabel2 as b
             on b.fkid=a.id ";

    $result =   mysql_query($str,$con);

    while($arr=mysql_fetch_array($result))
    {
        echo "<pre>";print_r($arr); //prints all values as a  formatted array Use these values in your tabel.
    }