哪一个让我在“联盟”和“案例”之间做出选择?

时间:2013-09-19 22:16:11

标签: sql sql-server select case union

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

使用UNION:

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

使用CASE:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

第二个查询最有可能使用comment_date上的索引扫描,在产品表上嵌套循环,i。即最多10次逻辑搜索以及从comments

读取10条记录所需的任何内容

第一个查询最有可能使用索引扫描并对每个查询进行排序,然后对其结果进行MERGE UNION

如果所有产品表中的comment_dateid_product都有索引,则第二个查询会更快。

答案 2 :(得分: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

答案 3 :(得分:0)

尽管我不喜欢它,但似乎使用CASE会更快。任何SELECT TOP N都会导致N个子查询。如果您在所有3个产品表中的id_product索引应该足够快。

UNION解决方案将触发3个完整查询,联合,排序,然后返回顶部。