我有以下 SQL 查詢:
select x
from table1 t1 join table2 t2 on t1.x = t2.x
where t1.x in ( SUBQUERY )
子查詢的結果是固定的并且獨立于查詢的其余部分。
如果我在那里撰寫子查詢的代碼,即使子查詢的計算速度相當快,也需要很長時間。但是,如果我手動將子查詢的結果值粘貼到那里,整個查詢將再次快速評估。我認為這是因為使用代碼而不是手動粘貼會導致對子查詢進行不必要的多次評估。
我怎樣才能避免這些?
提前致謝
uj5u.com熱心網友回復:
在許多資料庫上,如果使用in陳述句的子查詢的結果很大,那么你的性能就會很差。并且not in命令得到非常非常糟糕的性能。我建議您使用連接表。例如:
-- not recommended
select * from test_table a1
where id in (select id from test)
-- recommended
select * from test_table a1
inner join test a2 on a1.id = a2.id
而不是NOT IN:
-- not recommended
select * from test_table a1
where id not in (select id from test)
-- recommended
select * from test_table a1
left join test a2 on a1.id = a2.id
where a2.id is null;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/432611.html
標籤:sql PostgreSQL
