我有两张桌子,一张是Category
,另一张是Product
。
表说明有
类别
产品
category_id(类别表的外键)
我想在单个产品上显示所有类别以及相关产品。因此,为了获取关联的类别,我使用以下查询。我可以在自引用表中进行左连接,但无法获取产品数据列表,因为这是一个子查询,而子查询只会返回单个列。
select
cat1.id, ARRAY(select name, type, description from product where
product.category_id = cat1.id)
as category_1_products_data,
cat2.id, ARRAY(select name, type, description from product where
product.category_id = cat2.id)
as category_2_products_data,
cat3.id, ARRAY(select name, type, description from product where
product.category_id = cat3.id)
as category_3_products_data
from category cat1
left join category cat2
on cat2.parent_id = cat1.id
left join category cat3
on cat3.parent_id = cat2.id
where cat1.parent_id is …
Run Code Online (Sandbox Code Playgroud)