2013-03-25 66 views
0

我有一個像下面這樣的查詢,其中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成本過高?

+1

當您刪除連接時,您只能從一個表中進行選擇。增加連接會增加複雜性,因此CPU會增加。 – CathalMF 2013-03-25 14:50:06

+5

患者:「醫生,當我這樣做時會感到痛苦」。醫生:「那就停止這樣做吧......」 – jeroenh 2013-03-25 14:50:11

+1

爲什麼你需要多次加入同一張表? – 2013-03-25 14:51:45

回答

2

你有沒有索引table3m(fk)

這應該解決您的問題。

另一種製劑是:

select t.id, 
     max(case when m.[type] = 1 then field end) as field1, 
     max(case when m.[type] = 2 then field end) as field2, 
     . . . 
     max(case when m.[type] = 12 then field end) as field12 
from table150k t join 
    table3m m 
    on m.fk = t.id and m.[type] in (1,2,3,4,5,6,7,8,9,10,11,12) 
where t.id = @id 
group by t.id 

該結構具有從同一列進入的「3M」表中的所有數據。

+0

是的,我們有一個索引。 – 2013-03-25 14:51:09

+0

對'table3m(fk + [type])''怎麼樣? – 2013-03-25 14:52:27

+0

@JoeEnos我們也有這個:( – 2013-03-25 14:58:17

0

如果兩個表中的數據沒有頻繁變化,我會按照另一種方法創建一個只保存上述查詢結果的緩存表(只是另一個表)。

+2

業務邏輯需要的數據是即時:( – 2013-03-25 14:51:50

0

試試這個:

select * 
from table150k t 
inner join table3m t1 on t1.fk = t.id and t1.[type] in (1,2,3,4,5,6,7,8,9,10,11,12) 
where t.id = @id 
+0

這會不會產生12倍以上的記錄? – 2013-03-25 14:53:44

+0

其內部聯接,沒有離開加盟 – 2013-03-25 14:58:07

+0

它仍然將獲取12倍以上的記錄,因爲每一行都會被複制在table3m每個記錄。 – 2013-03-25 14:59:20

0
select t.id, t1.type, t1.field1 
from table150k as t 
inner join table3m as t1 on t1.fk = t.id 
where t.id = @id and t1.[type] in (1,2,3,4,5,6,7,8,9,10,11,12) 

這將帶回12條(假設它們都存在)。

這樣做的好處是服務器端的速度,缺點是你必須根據類型值將每條記錄映射到數據表或數據表中相應的列上。

+0

問題是這個代碼將所有不同的[類型]融合成一個單獨的列,而OP要的是m在不同的列中分開 – 2013-03-25 15:12:08

+0

是的,這將獲得每種類型的一個值記錄。這就是爲什麼我通過說他必須在數據進入他的應用程序後重新組織數據來對其進行限定。它在數據訪問層做了一些工作,但比同一個表上的12個內部連接快得多。 – 2013-03-25 15:18:19