根据我在Wikipedia上阅读的内容,相关的子查询在性能方面并不是最好的,因为每次主查询中的每条记录都需要执行子查询。
由于这个原因,我试图重写以下查询。我尝试将查询重写为仅使用INNER JOIN
来获得不同的结果。
有人可以帮我弄清楚我在新查询中错过了什么吗? 另外,我正在使用MSSQL server 2008。
原始查询
SELECT *
FROM
table1 t
WHERE
t.some_Id=123
AND EXISTS
(
SELECT TOP 1 1
FROM
table2 t2 WITH(NOLOCK)
LEFT OUTER JOIN
table3 t3 WITH(NOLOCK)
ON t3.another_id = t2.another_id
AND t3.yet_another_id = table1.yet_another_id //correlation with table1
WHERE t2.t2_id = 456 AND t3.t3_id IS NULL
)
新查询
SELECT *
FROM
table1 t
WHERE
t.some_Id=123
AND EXISTS
(
SELECT TOP 1 1
FROM
table2 t2 WITH(NOLOCK)
LEFT OUTER JOIN
table3 t3 WITH(NOLOCK)
ON t3.another_id = t2.another_id
INNER JOIN table1 t1
ON t3.yet_another_id = t1.yet_another_id
WHERE t2.t2_id = 456 AND t3.t3_id IS NULL
)
答案 0 :(得分:0)
这是您的查询:
SELECT *
FROM table1 t
WHERE t.some_Id = 123 AND
EXISTS (SELECT TOP 1 1
FROM table2 t2 LEFT OUTER JOIN
table3 t3
ON t3.another_id = t2.another_id
WHERE t2.t2_id = 456 AND t3.t3_id IS NULL AND
t3.yet_another_id = table1.yet_another_id
);
如果要提高性能,请考虑以下索引:
table1(some_id, yet_another_id)
table2(t2_id, another_id)
table3(another_id, yet_another_id, t3_id)