递归的PostgreSQL查询

时间:2019-03-10 18:39:02

标签: sql postgresql sequelize.js

我有2个表,CategoriesProducts

一个类别可以具有多个类别和产品,并且一个产品属于一个类别。我想做一个递归查询,为每个类别查找产品和类别,等等,直到树的末端。

  • 产品:(名称,categoryId,id);
  • 类别:(名称,类别ID,ID); --- CategoryId是类别父亲ID

我尝试使用此查询

WITH RECURSIVE t AS (
SELECT "Categories"."CategoryId" as CategoryId, "Categories".name as CategoryName, "Products".name as ProductName, "Products"."CategoryId" as   CategoryIdProduct FROM "Categories"
JOIN "Products"
ON "Categories"."CategoryFatherId" = '34b176f6-dcac-4547-96a0-9224c94fb8e8' and "Products"."CategoryId" IS NOT NULL
UNION ALL
SELECT a."CategoryId", a."name", s."productname", s."categoryidproduct"
FROM "Categories" a 
INNER JOIN t s ON a."id" = s.categoryid
)SELECT * FROM t;

但是给出这个结果当然不是我的目标:

[
 {
   "categoryid" : "34b176f6-dcac-4547-96a0-9224c94fb8e8",
    "productname" : "asdsad",
    "categoryname" : "sadad",
     "categoryidproduct" : "34b176f6-dcac-4547-96a0-9224c94fb8e8"
 },
 {
    "categoryid" : "34b176f6-dcac-4547-96a0-9224c94fb8e8",
     "productname" : "asdasd",
     "categoryname" : "sadasd",
     "categoryidproduct" : "2584c2ff-4e39-4b8a-b482-0802a1712114"
 },
 {
   "categoryid" : "34b176f6-dcac-4547-96a0-9224c94fb8e8",
   "productname" : "sad",
    "categoryname" : "sdaf",
    "categoryidproduct" : "34b176f6-dcac-4547-96a0-9224c94fb8e8"
 },
]

有人可以帮助我吗?

0 个答案:

没有答案