3

MySQL - Get row number on select 我知道如何使用这个 mysql 查询获取行号/排名:

SELECT @rn:=@rn+1 AS rank, itemID
FROM (
  SELECT itemID
  FROM orders
  ORDER BY somecriteria DESC
) t1, (SELECT @rn:=0) t2;

结果返回如下内容:

+--------+------+
| rank | itemID |
+--------+------+
|  1   |   265  |
|  2   |   135  |
|  3   |   36   |
|  4   |   145  |
|  5   |   123  |
|  6   |   342  |
|  7   |   111  |
+--------+------+

我的问题是:如何在 1 个简单的 SINGLE QUERY 中获得结果,该查询返回排名低于 itemID 145 的项目,即:

+--------+------+
| rank | itemID |
+--------+------+ 
|  5   |   123  |
|  6   |   345  |
|  7   |   111  |
+--------+------+

也欢迎使用 Oracle sql 查询。谢谢。

4

2 回答 2

2

Oracle 解决方案(不确定它是否符合您的“一个简单的单一查询”标准):

WITH t AS
(SELECT item_id, row_number() OVER (ORDER BY some_criteria DESC) rn
   FROM orders)
SELECT t2.rn, t2.item_id
  FROM t t1 JOIN t t2 ON (t2.rn > t1.rn)
 WHERE t1.item_id = 145;

我的假设是 item_id 没有重复值。

试图用 MySQL 术语来表达,也许这样的事情可能会奏效:

SELECT t2.rank, t2.itemID
  FROM (SELECT @rn:=@rn+1 AS rank, itemID
          FROM (SELECT itemID
                  FROM orders
                 ORDER BY somecriteria DESC), (SELECT @rn:=0)) t1 INNER JOIN
       (SELECT @rn:=@rn+1 AS rank, itemID
          FROM (SELECT itemID
                  FROM orders
                 ORDER BY somecriteria DESC), (SELECT @rn:=0)) t2 ON t2.rank > t1.rank
 WHERE t1.itemID = 145;

免责声明:我不经常使用 MySQL,而且它未经测试。甲骨文的作品有效。

于 2012-08-24T22:16:49.447 回答
1
SELECT @rn:=@rn+1 AS rank, itemID
  FROM (
    SELECT itemID
    FROM orders
    ORDER BY somecriteria DESC
  ) t1, (SELECT @rn:=0) t2
where rank >
(
select rank from
   (
   SELECT @rn:=@rn+1 AS rank, itemID
   FROM 
       (
       SELECT itemID
       FROM orders
       ORDER BY somecriteria DESC
       ) t1, (SELECT @rn:=0) t2
   ) x where itemID = 145
) y
于 2012-08-24T15:06:02.963 回答