簡體   English   中英

如何使用mysql查詢獲取特定行的位置排名?

[英]how to get position rank of specific row using just mysql query?

我有表用戶,其中包含列:id,name,points,extra_points。 當排名是積分和extra_points的總和時,如何獲得特定用戶的排名?

對於所有用戶列出使用此查詢的等級Im: "SELECT id, (points + extra_points) AS total FROM users ORDER BY total desc"; 和帶有html ol標簽的while循環(所以有位置編號)。 但我不知道如何顯示sinlge用戶的排名(在用戶個人資料頁面中)? 任何幫助都會很棒。

SELECT users1.id, (users1.points+users1.extra_points) AS total, COUNT(*)+1 AS rank
FROM users users1
INNER JOIN users users2 ON users1.points+users1.extra_points < users2.points+users2.extra_points
WHERE users1.id = $id

好吧,對於單個用戶,您可以更改選擇查詢,使其看起來像

"SELECT (points + extra_points) AS total FROM users WHERE id = $id LIMIT 1"

需要將哪個用戶指定為WHERE子句。 此外,由於您可能已經知道了id,因此不需要選擇它,因為它只是一個用戶,所以也不需要ORDER BY。 LIMIT 1將阻止它在找到其余行后檢查其余行。

這個沒有經過測試,但我希望你能理解我的想法 - 只需使用一個子選擇來計算所有用戶的點數:

SELECT
  id,
  (points + extra_points) AS total,
  (SELECT COUNT(*) FROM users WHERE (points + extra_points)) >= (u.points + u.extra_points) AS rank 
FROM 
  users u 
WHERE 
  id = ?;

如果您在名為Client的表中有ClientID和Points列,那么這就是答案:

<CFQUERY DATASOURCE="YourDatasource" name="YourQueryName">
SELECT ClientID, (Pts) AS total,   
(SELECT COUNT(*) FROM Client 
WHERE (Pts) >= (u.Pts)) AS rank  
FROM Client u  
WHERE ClientID = CLIENTID_OF_YOUR_CHOICE_HERE; 
</CFQUERY>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM