mysqli查询可随时更新学生的排名列

时间:2018-07-28 06:25:27

标签: php sql mysqli

我有用于学生数据库的sql表。
enter image description here
PHP脚本用于计数选票。
我使用此查询对学生进行排名。

此SELECT查询工作得很好,但我想根据投票数否对该​​列进行更新

SELECT id, first, vote, @curRank := @curRank + 1 AS rank
FROM student_table p, (
SELECT @curRank := 0
) q
ORDER BY vote DESC

更新
ty家伙,这对我有用:)

mysqli_query($conn, 'UPDATE student_table SET rank= @r:=0 ORDER BY vote DESC');
mysqli_query($conn, 'UPDATE student_table SET rank= @r:=(@r+1) ORDER BY vote DESC');

3 个答案:

答案 0 :(得分:1)

Logcat

答案 1 :(得分:0)

SQL查询:

$q = "SELECT * FROM tablename ORDER BY vote DESC";

check condition if(q->num_rows > 0){
$rank = 1;
then while loop($row = $q->fetch_assoc()) {
$id = $row['id'];
//update rank column
$q1 = "UPDATE tablename SET rank='".$rank"' WHERE id='".$id."' "
$rank++;
}

}//if close

答案 2 :(得分:0)

以下是备用更新查询,其中不使用MySQL中的变量。

update test
inner join (select id,name,vote,(select count(id) + 1 
                                 from test where id != t.id and vote > t.vote) as 'rank'
            from test t) derived_test
ON test.id = derived_test.id
set test.rank = derived_test.rank;

您可以查看此SQL fiddle来了解如何分配等级。

相关问题