我正在寻找使用 array_agg 列加入视图的语法。
看法:
CREATE VIEW sampleview AS
SELECT groupid, array_agg(akey) AS keyarray
FROM sampletable
GROUP BY groupid;
现在我想做这样的事情:
SELECT s.groupid, a.somedata
FROM sampleview AS s
JOIN anothertable AS a ON a.akey IN s.keyarray;
错误信息:
ERROR: syntax error at or near "s"
LINE 3: JOIN anothertable AS a ON a.akey IN s.keyarray;
语法错误(很可能)或不可能。我不相信这是不可能的,但如果它是我要求的替代选择。
上述伪查询的预期输出(带有测试代码):
groupid | somedata
---------+----------
1 | foo
1 | bar
2 | monkey
(3 rows)
测试代码:
CREATE TABLE sampletable (groupid int not null, akey int not null);
CREATE TABLE anothertable (akey int not null, somedata varchar(20));
CREATE VIEW sampleview AS SELECT groupid, array_agg(akey) AS keyarray FROM sampletable GROUP BY groupid;
INSERT INTO sampletable VALUES(1,20),(1,22),(2,33);
INSERT INTO anothertable VALUES(20, 'foo'),(22,'bar'),(33,'monkey');