我有这样的事情:
CREATE TABLE categories (
id varchar(250) PRIMARY KEY,
name varchar(250) NOT NULL,
parentid varchar(250)
);
CREATE TABLE products (
id varchar(250) PRIMARY KEY,
name varchar(250) NOT NULL,
price double precision,
category varchar(250) NOT NULL
);
INSERT INTO categories VALUES ('1', 'Rack', '');
INSERT INTO categories VALUES ('2', 'Women', '1');
INSERT INTO categories VALUES ('3', 'Shorts', '2');
INSERT INTO products VALUES ('1', 'Jean', 2.99, '3');
INSERT INTO products VALUES ('2', 'Inflatable Boat', 5.99, '1');
现在,如果我想查看每个类别的产品总价,我可以这样做:
SELECT
categories.name,
SUM(products.price) AS CATPRICE
FROM
categories,
products
WHERE products.category = categories.id
GROUP BY categories.name
;
产生输出:
name | catprice
--------+----------
Rack | 5.99
Shorts | 2.99
(2 rows)
但请注意,“Shorts”是“Rack”的祖先。我想要一个产生如下输出的查询:
name | catprice
--------+----------
Rack | 8.98
(1 row)
这样所有产品价格都会在根类别下加在一起。类别表中有多个根类别;为简单起见,只展示了一个。
这就是我到目前为止:
-- "nodes_cte" is the virtual table that is being created as the recursion continues
-- The contents of the ()s are the columns that are being built
WITH RECURSIVE nodes_cte(name, id, parentid, depth, path) AS (
-- Base case?
SELECT tn.name, tn.id, tn.parentid, 1::INT AS depth, tn.id::TEXT AS path FROM categories AS tn, products AS tn2
LEFT OUTER JOIN categories ON tn2.CATEGORY = categories.ID
WHERE tn.parentid IS NULL
UNION ALL
-- nth case
SELECT c.name, c.id, c.parentid, p.depth + 1 AS depth, (p.path || '->' || c.id::TEXT) FROM nodes_cte AS p, categories AS c, products AS c2
LEFT OUTER JOIN categories ON c2.CATEGORY = categories.ID
WHERE c.parentid = p.id
)
SELECT * FROM nodes_cte AS n ORDER BY n.id ASC;
我不知道我做错了什么。上面的查询返回零结果。
答案 0 :(得分:0)
你的递归查询有点过了。试一试:
编辑 - 要使用SUM,请使用:
WITH RECURSIVE nodes_cte(name, id, id2, parentid, price) AS (
-- Base case?
SELECT c.name,
c.id,
c.id id2,
c.parentid,
p.price
FROM categories c
LEFT JOIN products p on c.id = p.category
WHERE c.parentid = ''
UNION ALL
-- nth case
SELECT n.name,
n.id,
c.id id2,
c.parentid,
p.price
FROM nodes_cte n
JOIN categories c on n.id2 = c.parentid
LEFT JOIN products p on c.id = p.category
)
SELECT id, name, SUM(price) FROM nodes_cte GROUP BY id, name
祝你好运。