我有一個像下面這樣的查詢,其中table150k有150k條記錄,table3m有3m條記錄。在我們的生產服務器上,我們必須頻繁地運行此查詢以獲取單個記錄。這耗費了大量的CPU能力。降低SQL查詢的CPU開銷
select t.id, t1.field1 as f1, t2.field1 as f2, t3.field1 as f3, ..., t12.field1 as f12
from table150k t
inner join table3m t1 on t1.fk = t.id and t1.[type] = 1
inner join table3m t2 on t2.fk = t.id and t2.[type] = 2
inner join table3m t3 on t3.fk = t.id and t3.[type] = 3
...
inner join table3m t12 on t12.fk = t.id and t12.[type] = 12
where t.id = @id
當我刪除內從該查詢連接,它工作正常。當它們被包含時,我們的服務器會遭受cpu。
我該如何優化這個查詢,數據結構或場景,以便頻繁獲取數據不會使cpu成本過高?
當您刪除連接時,您只能從一個表中進行選擇。增加連接會增加複雜性,因此CPU會增加。 – CathalMF 2013-03-25 14:50:06
患者:「醫生,當我這樣做時會感到痛苦」。醫生:「那就停止這樣做吧......」 – jeroenh 2013-03-25 14:50:11
爲什麼你需要多次加入同一張表? – 2013-03-25 14:51:45