Chi*_*xit 3 postgresql join subquery select
我有两张桌子,一张是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 null;
Run Code Online (Sandbox Code Playgroud)错误:子查询必须仅返回一列第 2 行:cat1.id,(从...中选择名称、类型、描述)
数组的所有元素必须具有相同的类型;当使用子查询构造数组时,执行此操作的最简单方法是要求查询恰好返回一列。
但是您可以使用行构造函数使子查询返回类型为复合类型的单个列:
ARRAY(SELECT ROW(name, type, description) FROM ...)
Run Code Online (Sandbox Code Playgroud)