我的表格包含以下数据:
CategoryId CategoryName ParentCategoryId
1 abc null
2 abc1 1
3 abc2 1
4 def null
5 def1 4
6 def2 4
7 ghi null
8 ghi1 7
9 ghi2 7
我使用以下查询在此表上使用了自联接:
select p.CategoryId as ParentCategoryId, p.CategoryName as ParentCategoryName,
c.CategoryId as CategoryId, c.CategoryName as CategoryName
from Categories c, Categories p
where c.ParentCategoryId = p.CategoryId
此查询为每个categoryid生成父类别ID和名称的重复行。
我希望PraentCategoryId出现在所有相应子类别中一次。
我还需要做些什么,或者有办法修改此查询。
上述查询的结果就像
ParentCategoryId ParentCategoryName CategoryId CategoryName
1 abc 2 abc1
1 abc 3 abc2
4 def 5 def1
4 def 6 def2
7 ghi 8 ghi1
7 ghi 9 ghi2
答案 0 :(得分:0)
我使用JOIN放置了两个版本的查询。第一个将显示每个父项,每个子项都在自己的行上。第二个使用GROUP_CONCAT将子类别放在逗号分隔的列表中,每个父类别一行。
select
p.CategoryId as ParentCategoryId,
p.CategoryName as ParentCategoryName,
c.CategoryId as CategoryId,
c.CategoryName as CategoryName
from Categories c
JOIN Categories p
ON c.ParentCategoryId = p.CategoryId
select
p.CategoryId as ParentCategoryId,
p.CategoryName as ParentCategoryName,
GROUP_CONCAT(c.CategoryId) as CategoryIds,
GROUP_CONCAT(c.CategoryName) as CategoryNames
from Categories c
JOIN Categories p
ON c.ParentCategoryId = p.CategoryId
GROUP BY p.`CategoryId`
ORDER BY p.`CategoryId`
第二个查询的输出:
ParentCategoryId | ParentCategoryName | CategoryIds | CategoryNames
1 | abc | 2,3 | abc1,abc2
4 | def | 5,6 | def1,def2
7 | ghi | 9,8 | ghi2,ghi1
答案 1 :(得分:0)
希望这可以解决您的问题,
;WITH cte
AS (SELECT p.categoryid AS ParentCategoryId,
p.categoryname AS ParentCategoryName,
c.categoryid AS CategoryId,
c.categoryname AS CategoryName
FROM Categories c
JOIN Categories p
ON c.parentcategoryid = p.categoryid)
SELECT DISTINCT ParentCategoryId,
ParentCategoryName,
Stuff((SELECT ',' + Cast(t1.categoryid AS VARCHAR(10))
FROM cte t1
WHERE t.parentcategoryid = t1.parentcategoryid
FOR xml path('')), 1, 1, '') AS CategoryId,
Stuff((SELECT ',' + t2.categoryname
FROM cte t2
WHERE t.parentcategoryid = t2.parentcategoryid
FOR xml path('')), 1, 1, '') AS CategoryName
FROM cte t