1

这是我的表格和数据

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

我得到了一些想要的输出。但我的问题是我可以这样编写嵌套查询吗?有大数据时会引起任何问题吗?

4

1 回答 1

0

您可以使用以下查询。

以下查询有 1 个主选择和 3 个内部选择。

其结构如下:

select data,(select 
              josnData,
              (select josnData,
                      (select josnData from category where level_id = 3) as subcategories  
               from category where level_id = 2) as categories
             from category where level_id = 1) as questionnare_data
from category where level_id = 1
        

询问

select ID, name, level_id , root_id,
   (select (select ID, name, level_id , root_id,(select ID, name, level_id , root_id from category where level_id=3 FOR JSON PATH) as subcategories from category where level_id=2 FOR JSON PATH) as categories
   from category where level_id=1 FOR JSON PATH) as questionnare_data
from category
where level_id=1

db<>fiddle中的演示

于 2021-08-10T05:42:32.680 回答