【发布时间】:2013-09-25 04:42:16
【问题描述】:
我有一个表列表(即 productsA、productsB、productsN...),如果我想选择其中的前 10 个有序 cmets,这些表中的每个产品都可能有注释(存储在 cmets 表中)是最好的解决方案(就性能和速度而言)?
使用联合:
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
【问题讨论】:
-
由于
INNER JOINS,我假设采用UNION方法。但我会改用UNION ALL,因为它们有所有不同的产品类型,所以不可能重复。 -
"UNION" 组合了单个结果集,这是您在本例中所需要的。 “CASE”涉及数据转换,这里不是你需要的;所以使用“UNION”
标签: sql sql-server select case union