优化 CTE 查询
Optimize CTE query
我有 15 个表的大连接。简化后看起来像这样
WITH CTE AS
(
SELECT A.ID,
B.K,
X.Date,
X.ID,
ROW_NUMBER() OVER (PARTITION BY A.ID ORDER BY X.date ASC, x.id ASC) RN
FROM A
INNER JOIN B ON A.ID = B.ID
INNER JOIN C ON B.ID = C.ID
LEFT JOIN X ON (X.G = A.ID
OR X.H = B.ID
OR X.I = C.ID)
)
SELECT *
FROM CTE
WHERE RN = 1
执行时间约为 1 秒,主要是因为 X
的最后一个 JOIN。为了避免重复,我添加了 ROW_NUMBER
部分并将其变成了 CTE。
我如何最好使用 ANSI SQL 优化它,因为它在 SQL-Server 和 Oracle 上是 运行?
我明白了。像这样超快(0.1秒):
SELECT A.ID,
B.K,
X.DATE,
X.ID,
FROM A
INNER JOIN B ON A.ID = B.ID
INNER JOIN C ON B.ID = C.ID
LEFT JOIN
(
SELECT G, H, I, ID, DATE,
ROW_NUMBER() OVER (PARTITION BY G ORDER BY DATE ASC, ID ASC) RN
FROM X
) X ON RN = 1 AND (X.G = A.ID
OR X.H = B.ID
OR X.I = C.ID)
我有 15 个表的大连接。简化后看起来像这样
WITH CTE AS
(
SELECT A.ID,
B.K,
X.Date,
X.ID,
ROW_NUMBER() OVER (PARTITION BY A.ID ORDER BY X.date ASC, x.id ASC) RN
FROM A
INNER JOIN B ON A.ID = B.ID
INNER JOIN C ON B.ID = C.ID
LEFT JOIN X ON (X.G = A.ID
OR X.H = B.ID
OR X.I = C.ID)
)
SELECT *
FROM CTE
WHERE RN = 1
执行时间约为 1 秒,主要是因为 X
的最后一个 JOIN。为了避免重复,我添加了 ROW_NUMBER
部分并将其变成了 CTE。
我如何最好使用 ANSI SQL 优化它,因为它在 SQL-Server 和 Oracle 上是 运行?
我明白了。像这样超快(0.1秒):
SELECT A.ID,
B.K,
X.DATE,
X.ID,
FROM A
INNER JOIN B ON A.ID = B.ID
INNER JOIN C ON B.ID = C.ID
LEFT JOIN
(
SELECT G, H, I, ID, DATE,
ROW_NUMBER() OVER (PARTITION BY G ORDER BY DATE ASC, ID ASC) RN
FROM X
) X ON RN = 1 AND (X.G = A.ID
OR X.H = B.ID
OR X.I = C.ID)