2

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

首先,我拿到物品。

其次,我得到项目的选票并计算它们。

第三,我想根据总票数按顺序显示项目。

$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 做到这一点?或任何其他最佳解决方案?

4

2 回答 2

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`
于 2011-05-31T17:08:07.903 回答
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
于 2011-05-31T17:06:02.590 回答