我有n:m表链接两个表之间的数据:
id | category
-------------
2 | car
3 | bike
id | brand
-------------
4 | honda
5 | bmw
6 | mazda
7 | harley davidson
和n:m table
id | pk_category | pk_brand
-----------------------------
1 | 2 (car) | 4 (honda)
2 | 3 (bike) | 4 (honda)
3 | 2 (car) | 6 (mazda)
4 | 3 (bike) | 7 (harley)
我需要的是为桌面品牌创建选择。但我希望为每个品牌都包含类别。如果我JOIN
,那么我将有Honda
还想象有8个类别和500多个品牌。
有没有办法创建select * from brands
,它将返回如下表:
id | brand | categories
--------------------------
4 | honda | 2,3 (or different separator)
5 | bmw | null
6 | mazda | 2
7 | harley | 3
我真的在努力创造这样的东西。我想查询50多个品牌的一页,不想为每个品牌记录单独选择。
答案 0 :(得分:4)
;WITH brands(id,brand) AS
(
SELECT 4,'honda' UNION ALL
SELECT 5,'bmw' UNION ALL
SELECT 6,'mazda' UNION ALL
SELECT 7,'harley davidson'
),
brand_categories(id,pk_category,pk_brand)AS
(
SELECT 1,2,4 UNION ALL
SELECT 2,3,4 UNION ALL
SELECT 3,2,6 UNION ALL
SELECT 4,3,7
)
SELECT id,
brand,
LEFT(categories, LEN(categories) - 1) AS categories
FROM brands b
CROSS APPLY (SELECT CAST(pk_category as varchar) + ','
FROM brand_categories bc
WHERE bc.pk_brand = b.id
FOR XML PATH('')) ca(categories)
返回
id brand categories
----------- --------------- ------------
4 honda 2,3
5 bmw NULL
6 mazda 2
7 harley davidson 3