0

テーブルのリスト (つまり、productsA、productsB、productsN、...) があります。これらのテーブルの各製品には、コメント (comments テーブルに格納されている) がある場合があります。 (パフォーマンスと速度の面で) 採用されるソリューションは?

ユニオンを使用:

http://www.sqlfiddle.com/#!3/bc382/1

select TOP 10 comment_product, product_name, comment_date FROM (
   select comment_product, product_name, comment_date from comments inner join productsA on product_id = id_product WHERE product_type = 'A' 
UNION
   select comment_product, product_name, comment_date from comments inner join productsB on product_id = id_product WHERE product_type = 'B' 
UNION
   select comment_product, product_name, comment_date from comments inner join productsC on product_id = id_product WHERE product_type = 'C' 
) as temp ORDER BY comment_date DESC

ケースの使用:

http://www.sqlfiddle.com/#!3/bc382/2

select TOP 10 comment_product, comment_date, 
CASE product_type
  when 'A' then (select product_name from productsA as sub where sub.id_product = com.product_id) 
  when 'B' then (select product_name from productsB as sub where sub.id_product = com.product_id) 
  when 'C' then (select product_name from productsC as sub where sub.id_product = com.product_id) 
END
FROM comments as com
ORDER BY comment_date DESC
4

4 に答える 4

1

2 番目のクエリは、おそらくcomment_date製品テーブルに対するネストされたループでインデックス スキャンを使用します。つまり、最大で 10 回の論理シークと、そこから 10 個のレコードを読み取るのに必要なものをすべて加えたものです。comments

この最初のクエリでは、おそらくインデックス スキャンを使用して各クエリを並べ替え、次にMERGE UNIONその結果を並べ替えます。

すべての製品テーブルにインデックスがある場合、2 番目のクエリははるかに高速になりcomment_dateます。id_product

于 2013-09-19T22:33:48.963 に答える
1

これだと思います。INNER JOIN は、UNION およびネストされたクエリよりも高速です。

これがSqlFiddleのデモです。

SELECT TOP 10 comment_product, comment_date, 
case when product_type = 'A' then a.product_name 
when product_type = 'B' then b.product_name 
when product_type = 'C' then c.product_name 
else '' end
FROM comments INNER JOIN productsA a ON product_id = a.id_product  
INNER JOIN productsB b ON product_id = b.id_product   
INNER JOIN productsC c ON product_id = c.id_product   
ORDER BY comment_date DESC
于 2013-09-19T22:59:41.203 に答える
1

どちらも必要ないUNIONか、コメントに複数回CASE使用できることをお勧めします。JOIN

SELECT TOP 10 
            comment_product
          , COALESCE(a.product_name,b.product_name,c.product_name) AS product_name
          , comment_date 
FROM comments z
LEFT JOIN productsA a
    ON z.product_id = a.id_product  AND z.product_type = 'A' 
LEFT JOIN productsB b
    ON z.product_id = b.id_product  AND z.product_type = 'B' 
LEFT JOIN productsC c
    ON z.product_id = c.id_product  AND z.product_type = 'C' 
WHERE COALESCE(a.id_product,b.id_product,c.id_product) IS NOT NULL
ORDER BY z.comment_dateDESCC
于 2013-09-19T22:26:10.713 に答える
0

嫌な事ばかりですが、CASEを使った方が早くなりそうです。AnySELECT TOP Nを指定すると、N 個のサブクエリが生成されます。3 つの製品テーブルすべてに id_product のインデックスがある場合、十分に高速であるはずです。

UNION ソリューションは、union、sort、top の 3 つの完全なクエリをトリガーします。

于 2013-09-19T22:51:21.567 に答える