简体   繁体   English

SQL(mysql)排序表并获取其在排序表中的位置的行?

[英]SQL (mysql) sort table and get row with its position in the sorted table?

Basically I have this table: 基本上我有这张桌子:

Table QID, UID, system, added(unix timestamp), errors 表QID,UID,系统,添加的(unix时间戳),错误

What Im trying to do is to select a row via UID, But before that sort the table by 'added' so its in timestamps DESC order and then get the single row with its position in the sorted table. 我想做的是通过UID选择一行,但是在此之前,通过“添加”对表进行排序,以便按时间戳DESC顺序对其进行排序,然后获得单行及其在已排序表中的位置。

I currently have this which does rank the rows, but how would I get the single row from it: 我目前有的确可以对行进行排名,但是如何从中获取单行:

SET @rank=0;
SELECT @rank := @rank +1 AS rank, UID
FROM table
GROUP BY UID
ORDER BY added DESC

You would use a subquery: 您将使用子查询:

SELECT *
FROM (SELECT @rank := @rank +1 AS rank, UID, added
      FROM (SELECT UID, added
            FROM t cross join
                   (SELECT @rank := 0) var
            GROUP BY UID
            ORDER BY added ASC
           ) t
     ) t
WHERE UID = 12346;

One problem is that added is indeterminate when there are multiple rows for a given UID . 一个问题是,当给定的UID有多行时, added的不确定。 I suspect that you want MAX(added) instead. 我怀疑你想要MAX(added)代替。

You can either do something along the lines of: 您可以按照以下方式进行操作:

SELECT COUNT(*)+1 AS rank FROM table
WHERE added < (SELECT added FROM table WHERE UID=123)

Or maybe this: 也许这样:

SELECT * FROM (
    SELECT @rank := @rank+1 AS rank, UID
    FROM table
    GROUP BY UID
    ORDER BY added ASC
) tmp WHERE UID=123

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM