0

我有一个表格列表(即 productsA,productsB,productsN,...)这些表格中的每个产品都可能有评论(存储在评论表中),如果我想选择前 10 个有序评论,其中最好要采用的解决方案(在性能和速度方面)?

使用联合:

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

我觉得这个。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

第二个查询很可能会comment_date在产品表上使用带有嵌套循环的索引扫描,即最多 10 次逻辑查找加上读取 10 条记录所需的一切comments

第一个查询很可能会使用索引扫描并对每个查询进行排序,然后是MERGE UNION它们的结果。

如果您在所有产品表上都有索引comment_dateid_product那么第二个查询会快得多。

于 2013-09-19T22:33:48.963 回答
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 解决方案将触发 3 个完整查询,即 union、sort 和 top。

于 2013-09-19T22:51:21.567 回答