2

I'm searching for the syntax to join a view with an array_agg column.

View:

CREATE VIEW sampleview AS
SELECT groupid, array_agg(akey) AS keyarray
FROM sampletable
GROUP BY groupid;

Now I want do something like this:

SELECT s.groupid, a.somedata
FROM sampleview AS s
JOIN anothertable AS a ON a.akey IN s.keyarray;

Error message:

ERROR:  syntax error at or near "s"
LINE 3: JOIN anothertable AS a ON a.akey IN s.keyarray;

either the syntax is wrong (most likely) or it is not possible. I don't believe this is not possible but if it is I asking for an alternative option.

expected output for the pseudo query above (with the testing code):

 groupid | somedata 
---------+----------
       1 | foo
       1 | bar
       2 | monkey
(3 rows)

testing code:

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');
2
  • Why are you aggregating akey? That is already bad enough in a table and in a view you gain absolutely nothing as the view will be calculated at each query. Commented Jul 31, 2013 at 14:41
  • My sample was just a break down of the actual problem. I have a table where courses are stored, a table with the user mapping and a table (moodlecourses) where the information is stored which course of the courses table should created in a different system (moodle). In Addition it's possible to merge two or more courses together for creation in moodle. My goal was to create two views. One for the courses that should created in moodle and one for the user mapping just for this courses. My moodlecourses table has 2 columns: moodlecourseid and courseid of courses table. Commented Jul 31, 2013 at 16:13

1 Answer 1

3
SELECT s.groupid, a.somedata
FROM sampleview AS s
JOIN anothertable AS a ON a.akey = any(s.keyarray);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Can you say me where I can find this in the documentation? I'm just interested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.