MYSQL Order By W/Count

[亡魂溺海] 提交于 2019-12-14 03:04:56

问题


My table has usernames and points of user, and I am working on a leader boards list. I would like to get the top ten players based on points. I have formulated this query as:

SELECT
    users.username,
    users.points
FROM users
ORDER BY users.points DESC
LIMIT 10

However, I would also like to get where the player stands in accordance to the number 1 player, without creating a new column for it. Is there a MYSQL query to get the ORDER BY DESC by points as well as COUNT from that ORDER to find the user in the list? (WHERE username=).

Edit for clarification: I would like the count of the users from desc by the above statement. I.E. 1 - user1 - 1000 points, 2 - user2 - 750 points.. etc etc... N - currentPlayer - currentPoints. I don't mind using a JOIN statement, but I don't want to have a new column of players sorted by ranking.


回答1:


Try this:

SELECT * FROM (
    select @rownum:=@rownum+1 `rank`, u.username, u.points 
    from users u, (SELECT @rownum:=0) r
    order by points desc) AS X
WHERE username ="Bob";

Sample data:

CREATE TABLE users(
  id int auto_increment primary key,
  username varchar (30),
  points INT
  );

INSERT INTO users(username,points)
VALUES ('Bob', 1000), ('Jack',750), ('Joe', 500)

SQL FIDDLE DEMO




回答2:


SELECT users.username, users.points FROM users WHERE users.points=MAX(users.points) OR users.username='<comparison username>' ORDER BY users.points DESC;


来源:https://stackoverflow.com/questions/14589481/mysql-order-by-w-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!