2

我有相当复杂的连接查询,我想从中选择具有特定 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服务器上运行。

4

2 回答 2

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 )
于 2012-11-01T13:35:05.493 回答
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 )
于 2018-10-10T03:48:25.250 回答