非常标准的设置,包含产品、类别和类别中的产品表,但我想知道是否有更好/更有效的方法来获取产品的几个顶级类别(我真的不想把它们单独带回来行,因此内部连接不可行)。
我目前拥有的 SQL 是:
SELECT p.*,
(SELECT TOP 1 category_name FROM categories c INNER JOIN products_and_categories pc ON pc.category_id = c.category_id WHERE p.product_id = pc.product_id AND category_parent = 100 ORDER BY sort) AS cat_1,
(SELECT TOP 1 category_name FROM categories c INNER JOIN products_and_categories pc ON pc.category_id = c.category_id WHERE p.product_id = pc.product_id AND category_parent = 200 ORDER BY sort) AS cat_2,
(SELECT TOP 1 category_name FROM categories c INNER JOIN products_and_categories pc ON pc.category_id = c.category_id WHERE p.product_id = pc.product_id AND category_parent = 500 ORDER BY sort) AS cat_3,
(SELECT TOP 1 category_name FROM (SELECT TOP 2 c.* FROM categories c INNER JOIN products_and_categories pc ON pc.category_id = c.category_id WHERE p.product_id = pc.product_id AND category_parent = 500 ORDER BY sort) c1 ORDER BY sort DESC) AS cat_4,
(SELECT TOP 1 category_name FROM categories c INNER JOIN products_and_categories pc ON pc.category_id = c.category_id WHERE p.product_id = pc.product_id AND category_parent = 50 ORDER BY sort) AS cat_5,
(SELECT TOP 1 category_name FROM (SELECT TOP 2 c.* FROM categories c INNER JOIN products_and_categories pc ON pc.category_id = c.category_id WHERE p.product_id = pc.product_id AND category_parent = 50 ORDER BY sort) c1 ORDER BY sort DESC) AS cat_6
FROM products AS p
我很高兴以这种方式写了几篇专栏文章,但想知道是否还有其他方法可以做到这一点?通过加入 PIVOT 表或其他我没有想到的东西,或者我是否应该接受这样做。
还有一些其他限制(可能重要也可能不重要):
- 一些子查询可能不会带回任何结果
- 我需要前 2 个类别的一些行(如上面的代码所示)