您好我想简单地添加1,2,3,4,5,6,7,8,9,10等级。
我的输出现在提供以下内容:
USER ID | SCORE
2 | 10242
13231 | 3427
23732 | 3378
24638 | 2934
23468 | 1898
我努力实现的目标是:
RANK | USER ID | SCORE
#1 | 2 | 10242
#2 | 13231 | 3427
#3 | 23732 | 3378
#4 | 24638 | 2934
#5 | 23468 | 1898
这是我的php:
<?php $result = mysql_query("SELECT * FROM `users_score` ORDER BY `users_score`.`score` DESC LIMIT 0 , 10") or die(mysql_error());
if(mysql_num_rows($result) > 0): ?>
<table>
<tr>
<th style="text-align:left;">ID</th>
<th style="text-align:left;">SCORE</th>
<tr>
<?php while($row = mysql_fetch_assoc($result)): ?>
<tr>
<td><?php echo $row['user_id']; ?></td>
<td style="font-weight: bold; color: #008AFF;"><?php echo $row['score']; ?></td>
</tr>
<?php endwhile; ?>
</table>
<?php endif; ?>
这有一个简单的计数函数吗?
答案 0 :(得分:1)
您可以使用变量在查询中执行此操作。
SELECT @row:=@row+1 as RankNo,
a.UserID,
a.Score
FROM tableName a, (SELECT @row:=0) b
ORDER BY a.Score DESC
但它有一个DownSide,它没有处理平局分数
如果你想在等级上添加#
,可以RankNo with
#`
更新1
SELECT CONCAT('#', @row:=@row+1) as RankNo,
a.UserID,
a.Score
FROM tableName a, (SELECT @row:=0) b
ORDER BY a.Score DESC
答案 1 :(得分:1)
SELECT (@rank := @rank + 1) AS rank, user_id, score
FROM ( SELECT user_id, score
FROM scores, (SELECT @rank := 0) AS vars
ORDER BY score DESC) AS h
答案 2 :(得分:0)
您正在寻找的是等同于MS SQL的row_number()函数。之前已经回答过,例如here或here
答案是使用类似的东西:
SELECT @rn:=@rn+1 as RANK, ID, SCORE
FROM `users_score`, (SELECT @rn:=0) as rn
ORDER BY `users_score`.`score` DESC LIMIT 0
<强>更新强>
只是为了感兴趣,可以在SQL中处理匹配分数:
SELECT @rn := @rn + case (@ls-SCORE) when 0 then 0 else @s end as RANK,
ID,
SCORE,
@s := case (@ls-SCORE) when 0 then @s+1 else 1 end as STEPSIZE,
@ls := SCORE as LASTSCORE
FROM `users_score`.`score` a,
(SELECT @rn := 0) b,
(SELECT @ls := max(SCORE)+1 FROM `users_score`.`score`) c,
(SELECT @s := 1) d
ORDER BY a.Score DESC LIMIT 0
但是,如果你想这样做,那么PHP代码就更容易了。
答案 3 :(得分:0)
If you just want changes in your php here is the code...
<?php
$result = mysql_query("SELECT * FROM `users_score` ORDER BY `users_score`.`score` DESC LIMIT 0 ,10") or die(mysql_error());
$rank=0;
$temp_score=0;
if(mysql_num_rows($result) > 0): ?>
<table>
<tr>
<th style="text-align:left;">RANK</th>
<th style="text-align:left;">ID</th>
<th style="text-align:left;">SCORE</th>
<tr>
<?php while($row = mysql_fetch_assoc($result)):
if($temp_score!=$row['score'])
$rank++;
?>
<tr>
<td><?php echo "#".$rank; ?></td>
<td><?php echo $row['user_id']; ?></td>
<td style="font-weight: bold; color: #008AFF;"><?php echo $row['score']; ?></td>
</tr>
<?php
$temp_score=$row['score];
endwhile; ?>
</table>
<?php endif; ?>