所以我试图从最高声望和最高经验(xp)中排序
public function getRank($user, $skill, $mode) {
$skill2 = strtolower($skill)."_xp";
$skill3 = strtolower($skill)."_prestiges";
$stmt = $this->conn->prepare("SELECT (
SELECT COUNT(*) FROM hs_users WHERE mode = :mode AND (
$skill3 >= u.$skill3 AND $skill2 >= u.$skill2
)
) AS rank
FROM hs_users u
WHERE username = :user AND mode = :mode2
LIMIT 1");
$stmt->bindParam(":user", $user);
$stmt->bindParam(":mode", $mode);
$stmt->bindParam(":mode2", $mode);
$stmt->execute();
return $stmt->fetchColumn();
}
目前我获得了重复排名,两个人排名第一。
例如 如果某人有声望1和3,000,000经验,然后有人声望0和4,000,000经验他们达到相同的排名,至于第二个人被认为是2级。
我一直在尝试ORDER BY,但它似乎并没有起作用。我对SQL查询没有太多经验,如果你有任何指示或者可以帮助我做得很好。
答案 0 :(得分:0)
如果声望是主要排名属性:
$stmt = $this->conn->prepare("SELECT id, $skill3, $skill2
FROM hs_users
WHERE username = :user
AND mode = :mode
");
$stmt->bindParam(":user",$user);
$stmt->bindParam(":mode",$mode);
if($stmt->execute()){
$user = $stmt->fetch(PDO::FETCH_ASSOC);// get the users id, prestige and experience level
}
$higherPrestiges = array();
$stmt = $this->conn->prepare("SELECT id
FROM hs_users
WHERE $skill3 >= :skill3
AND mode = :mode");
$stmt->bindParam(":skill3",$user[$skill3]);
$stmt->bindParam(":mode",$mode);
if($stmt->execute()){
while($row = $stmt->fetch(PDO::FETCH_COLUMN)){ //get all users that have higher prestige
$higherPrestiges[$row] = $row;
}
}
if(count($higherPrestiges) > 0){
$higherPrestiges_implode = implode(",",$higherPrestiges);
}else{
$higherPrestiges_implode = "0";
}
$lowerExperiences = array();
$stmt = $this->conn->prepare("SELECT id
FROM hs_users
WHERE $skill3 = :skill3
AND $skill2 < :skill2
AND mode = :mode");
$stmt->bindParam(":skill2",$user[$skill2]);
$stmt->bindParam(":skill3",$user[$skill3]);
$stmt->bindParam(":mode",$mode);
if($stmt->execute()){
while($row = $stmt->fetch(PDO::FETCH_COLUMN)){//get users with lower experience with the same prestige
$lowerExperiences[$row] = $row;
}
}
if(count($lowerExperiences) > 0){
$lowerExperiences_implode = implode(",",$lowerExperiences);
}else{
$lowerExperiences_implode = "0";
}
$stmt = $this->conn->prepare("SELECT COUNT(id)
FROM hs_users
WHERE mode = :mode
AND id IN(".$higherPrestiges_implode.")
AND id NOT IN(".$lowerExperiences_implode.")");
$stmt->bindParam(":mode",$mode);
if($stmt->execute()){
$rank = $stmt->fetch(PDO::FETCH_COLUMN);//get number of users that have higher or equal prestige and exclude the ones with lower experience
}
只需替换对&#34; id&#34;的引用在具有表中主键的列名的查询中
我确实认识到最后3个查询可以与IN子句中的子查询结合使用,但这样可以更容易理解