按总投票数排序结果

时间:2011-05-31 17:01:55

标签: php mysql voting

我正在建立一个投票系统。有两个表格 - 一个用于votes,另一个用于items投票。在此示例中,项目是线程。

首先,我得到了这些物品。

其次,我获得了物品和票的投票。算上他们。

第三,我想根据计票总数显示订单中的项目。

$q = $db_conn->prepare('SELECT id, title FROM thread');
$q->execute();
$q->bind_result($threadid, $title);
$q->store_result();
while($q->fetch()){

    $q2 = $db_conn->prepare('SELECT value FROM vote WHERE item_id = ? AND item_type_id = 1');
    $q2->bind_param('i', $threadid);
    $q2->execute();
    $q2->bind_result($value);
    $totvalue = 0;
    while($q2->fetch()){
        $totvalue += $value;
    }?>

    <span style='color:grey;'>[<?php echo $totvalue; ?>]</span>

    <form class='thread' method='POST'>
        <input type='image' name='vote' value='up' src='media/img/uparrow.png' />
        <input type='image' name='vote' value='down' src='media/img/downarrow.png' />
        <input type='hidden' name='threadid' value='<?php echo $threadid; ?>' />
    </form>

    <?php echo $title . "<br />";
    //DISPLAYS BY ID
}

我发现的唯一方法就是将结果放入数组并按此方式排序。但是当网站需要处理物品时,将整个表放在一个数组中是没有意义的。

$threads[] = array('threadid' => $threadid, 'title' => $title, 'totvalue' => $totvalue);

foreach ($threads as $key => $row) {
    $tid[$key]  = $row['threadid'];
    $title[$key] = $row['title'];
    $tval[$key] = $row['totvalue'];
} array_multisort($tval, SORT_DESC, $tid, SORT_DESC, $tval, SORT_DESC, $threads);

foreach ($threads as $t) { ?>

    <span style='color:grey;'>[<?php  echo $t['totvalue']; ?>]</span>

    <form class='thread' method='POST'>
        <input type='image' name='vote' value='up' src='media/img/uparrow.png' />
        <input type='image' name='vote' value='down' src='media/img/downarrow.png' />
        <input type='hidden' name='threadid' value='<?php echo $t['threadid']; ?>' />
    </form>

    <?php echo $t['title'] . "<br />";
    //DISPLAYS BY TOTAL VOTES YET THE SOLUTION IS HORRID
}

有没有办法用MySQL做到这一点?或者任何其他最佳解决方案?

2 个答案:

答案 0 :(得分:2)

有一件事你应该将你的查询加入到一个并保存查询,你应该阅读mysql文档/教程,因为它可以为你节省大量的后端工作。

SELECT thread.id, thread.title, count(vote.value) as votes 
FROM thread JOIN vote ON thread.id = vote.item_id 
WHERE vote.item_type_id = 1
GROUP BY thread.id
ORDER BY votes DESC`

答案 1 :(得分:1)

这假设vote表中每个投票有一行:

select t.id, t.title, c.VoteCount
from thread t
inner join (
    select item_id, count(*) as VoteCount
    from vote
    where item_type_id = 1
    group by item_id
) c on t.id = c.item_id
order by c.VoteCount desc

如果没有,你可以这样做:

select t.id, t.title, v.Value as VoteCount
from thread t
inner join vote v on t.id = v.item_id
where v.item_type_id = 1
order by v.Value desc