按特定项ID的行号id过滤

时间:2012-08-24 14:51:44

标签: mysql sql oracle

来自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个简单的单一查询中得到结果,返回排名低于itemID为145的项目,即:

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

Oracle sql查询也受到欢迎。感谢。

2 个答案:

答案 0 :(得分: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,而且未经测试。甲骨文的作品。

答案 1 :(得分: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