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

时间:2014-05-04 21:05:35

标签: php mysql sql sorting

基本上我有这张表:

表 QID,UID,系统,添加(unix时间戳),错误

我尝试做的是通过UID选择一行,但在此之前,该表通过添加'所以它的时间戳为DESC顺序,然后得到单行及其在排序表中的位置。

我目前有这个排序行,但我如何从中获取单行:

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

2 个答案:

答案 0 :(得分:0)

您将使用子查询:

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;

一个问题是,当给定added有多行时,UID是不确定的。我怀疑你想要MAX(added)

答案 1 :(得分:0)

您可以按照以下方式执行以下操作:

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

或许这个:

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