如果我有三列:
id,username,time
我的数据是:
+-------+------------------+-------------+
| id | username | time |
+-------+------------------+-------------+
| 1 | A | 1 min |
| 2 | A | 2 min |
| 3 | B | 3 min |
| 4 | B | 4 min |
+-------+------------------+-------------+
此查询正在努力获得排名:
SELECT time,
FIND_IN_SET(MIN(time), (SELECT GROUP_CONCAT(time ORDER BY time ASC)
FROM table t1)) AS rank
FROM table t2
WHERE t2.username = 'B';
只有一个问题:它返回用户B的Rank 3de而不是2nd。
所以我尝试使用 GROUP BY t2.username 以及区分t2.username 但是没有用。
如何获得用户B的排名?它应该是2(不是3 ),因为我们只有2个用户。
答案 0 :(得分:0)
E.g:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL
,username CHAR(1) NOT NULL
,time TIME NOT NULL
);
INSERT INTO my_table VALUES
(1,'A','00:01:00'),
(2,'A','00:02:00'),
(3,'B','00:03:00'),
(4,'B','00:04:00');
SELECT * FROM my_table;
+----+----------+----------+
| id | username | time |
+----+----------+----------+
| 1 | A | 00:01:00 |
| 2 | A | 00:02:00 |
| 3 | B | 00:03:00 |
| 4 | B | 00:04:00 |
+----+----------+----------+
SELECT *
FROM
( SELECT username
, time
, @i:=@i+1 rank
FROM
( SELECT username
, MIN(time) time
FROM my_table
GROUP
BY username
) x
, (SELECT @i:=0) vars
ORDER
BY time
) n
WHERE username = 'B';
+----------+----------+------+
| username | time | rank |
+----------+----------+------+
| B | 00:03:00 | 2 |
+----------+----------+------+
我认为这也会有用,但它有些笨拙,所以我不确定......
SELECT x.*
, FIND_IN_SET(time,(SELECT GROUP_CONCAT(DISTINCT time ORDER BY time) FROM (SELECT MIN(time) time FROM my_table GROUP BY username) j )) rank
FROM my_table x HAVING rank <> 0 AND username = 'B';