这是我的表格和数据
CREATE TABLE category
(
ID int,
name varchar(255),
root_id int,
level_id int,
description nvarchar(max),
language_id int
);
INSERT INTO category (ID, name, root_id, level_id, description, language_id)
VALUES (1, 'questionnaire', 0, 1, 'desc1', 1);
VALUES (2, 'category1', 1, 2, 'desc1', 1);
VALUES (3, 'subcategory1', 2, 3, 'desc1', 1);
VALUES (4, 'subcategory_ge1', 2, 3, 'desc1', 2);
VALUES (5, 'subcategory2', 2, 3, 'desc2', 1);
VALUES (6, 'subcategory_ge2', 2, 3, 'desc2', 2);
VALUES (7, 'category2', 1, 2, 'desc2', 1);
VALUES (8, 'category2_ge', 1, 2, 'desc2', 2);
VALUES (9, 'subcategory3', 7, 3, 'desc3', 1);
VALUES (10, 'subcategory4', 8, 3, 'desc4', 1);
我正在尝试获取数据以获取类似的格式
ID name root_id level_id questionnare_data
-------------------------------------------------------------------
1 questionnaire 1 0 {"categories":{{"ID:2,"name":"category1","level_id":2,"subcategories":{{"ID":3,"name":"subcategory1","level_id":3},{"ID":4,"name":"subcategory_ge1","level_id":3},{"ID":5,"name":"subcategory2","level_id":3},{"ID":6,"name":"subcategory_ge2","level_id":3}}},{"ID":7",name":"category2","level_id":2,"subcategories":{{"ID":9,"name":"subcategory3","level_id":3}}},{"ID":8",name":"category2_ge","level_id":2,"subcategories":{{"ID":10,"name":"subcategory4","level_id":3}}}}}
我尝试了以下查询
select A.ID, A.name, A.level_id , A.root_id ,
(select B.ID, B.name,
(select C.ID, C.name
from category as C
where C.level_id=2 and C.root_id=B.ID FOR JSON AUTO) AS subcategories
from category as B
where B.level_id=1 and B.root_id=A.ID FOR JSON AUTO) AS categories
from category as A
where A.level_id=0 and A.root_id IS NULL
我得到了一些想要的输出。但我的问题是我可以这样编写嵌套查询吗?有大数据时会引起任何问题吗?