我正在建立一个投票系统。有两张表-一张是为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有办法吗?或者其他最优方案?

最佳答案

这假设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

08-25 18:14
查看更多