我的数据库中有以下架构:
CREATE TABLE categories (
id bigint NOT NULL,
name character varying NOT NULL,
ancestry character varying
);
CREATE TABLE video_chats (
id bigint NOT NULL,
name character varying NOT NULL,
category_id bigint NOT NULL
);
我有一些带视频聊天的嵌套类别:
INSERT INTO categories (id, name, ancestry)
VALUES (1, 'Test category', null);
INSERT INTO categories (id, name, ancestry)
VALUES (2, 'Test category subcategory', '1');
INSERT INTO categories (id, name, ancestry)
VALUES (3, 'Test category subcategory', '1/2');
INSERT INTO video_chats (id, name, category_id)
VALUES (1, 'Test Video 1', '2');
INSERT INTO video_chats (id, name, category_id)
VALUES (2, 'Test Video 2', '3');
现在我希望有一个sql查询来计算类别及其子类别的视频聊天。它应该返回以下结果:
这是我的架构的sqlfiddle:
http://sqlfiddle.com/#!17/f1cee/2
我如何在PostgreSQL中执行此操作?
答案 0 :(得分:1)
t=# with a as (select v.id,unnest(array_append(string_to_array(ancestry,'/')::bigint[],c.id)) cg from video_chats v join categories c on v.category_id = c.id)
select cg,count(1) from a group by cg order by cg;
cg | count
----+-------
1 | 2
2 | 2
3 | 1
(3 rows)
我的结果与预期不同:
计算类别和其子类别的视频聊天
所以视频聊天ID 1 属于类别2因此(因为2是1到1的子类别,它是vc1类别:2,1 视频聊天2 属于类别3,因而为2,因而为1,所以vc2 caterories:3,2,1
在我的查询中,它是CTE正文:
t=# select v.id,array_append(string_to_array(ancestry,'/')::bigint[],c.id) from video_chats v join categories c on v.category_id = c.id; id | array_append
----+--------------
1 | {1,2}
2 | {1,2,3}
(2 rows)
因此导致: