使用连接返回具有特定值的行周围的行

时间:2012-11-01 10:45:54

标签: sql-server-2008 tsql join row-number

我有一个相当复杂的连接查询,我想从中选择一些具有特定id的结果。

查询目前看起来像这样:

WITH results AS 
  (
    SELECT t1.id,  t1.position, t1.points, t2.name
      ROW_NUMBER() OVER(ORDER BY t1.position ASC, t1.points DESC) AS rn
      FROM Table1 t1
      JOIN Table2 t2 ON t1.id = t2.Table1id
      /* Several more joins here, some of which limit the result set */
  )
SELECT * FROM results
WHERE rn < ( SELECT rn+3 FROM results WHERE  id = @someid ) 
AND rn > ( SELECT rn-3 FROM results WHERE id = @someid )

有没有更好的方法来解决这个问题?最重要的是,我担心这些多次调用可能是巨大的CTE的性能。

查询在 SQL 2008 服务器上运行。

2 个答案:

答案 0 :(得分:1)

也许将连接从CTE中拉出来 这样,查询优化器有可能在处理连接之前过滤掉行。

WITH results AS 
  (
    SELECT t1.id,  t1.position, t1.points
         , ROW_NUMBER() OVER(ORDER BY t1.position ASC, t1.points DESC) AS rn
      FROM Table1 t1     
  )
SELECT results.id,  results.position, results.points, t2.name
FROM results
JOIN Table2 t2 ON t2.id = results.Table1id
      /* Several more joins here */
WHERE rn < ( SELECT rn+3 FROM results WHERE id = @someid ) 
  AND rn > ( SELECT rn-3 FROM results WHERE id = @someid )

答案 1 :(得分:0)

您可以使用另一个cte来帮助形成过滤器:

WITH results AS (
    SELECT
        t1.id
      , t1.position
      , t1.points
      , t2.name
      , ROW_NUMBER() OVER (ORDER BY t1.POSITION ASC, t1.points DESC) AS rn
    FROM Table1 t1
    JOIN Table2 t2
        ON t1.id = t2.Table1id
    /* Several more joins here, some of which limit the result set */
    ),
filter AS (
    SELECT
        rn
    FROM results
    WHERE id = @someid
    )
SELECT
    *
FROM results
WHERE rn < ( SELECT rn + 3 FROM filter )
AND rn > ( SELECT rn - 3 FROM filter )