1

table150k には 150k レコードがあり、table3m には 3m レコードがある以下のようなクエリがあります。運用サーバーでは、一度に 1 つのレコードに対してこのクエリを非常に頻繁に実行する必要があります。これには多くの 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 のコストが高くならないようにするにはどうすればよいですか?

4

4 に答える 4

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」テーブルの同じ列からのすべてのデータが含まれています。

于 2013-03-25T14:50:14.233 に答える
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 個のレコードが返されます (すべて存在すると仮定します)。

ここでの利点はサーバー側の速度です。欠点は、アプリケーションに取得したら、型の値に基づいて、各レコードをデータテーブルの対応する列またはオブジェクトの値にマップする必要があることです。

于 2013-03-25T15:06:07.617 に答える
0

2 つのテーブルのデータが頻繁に変更されない場合は、別の方法に従って、上記のクエリの結果を保持するだけのキャッシュ テーブル (別のテーブル) を作成します。

于 2013-03-25T14:51:06.773 に答える
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
于 2013-03-25T14:51:47.613 に答える