我有一个表格列表(即 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