我有类似的东西。
\ d表1
uid |int (primary key)
name|text
cids|int[]
示例:
id | name | cids
1 | joe |{10,20,30}
2 | marry |{10,20,30,40}
3 | john |{30,40}
\ d表2
cid |int (primary key)
name |text
type |int
示例
cid | name | type
10 | aname | 0
20 | bname | 0
30 | cname | 1
40 | dname | 0
现在我想要一个像这样的结果 id,table1和cid中的名称,表2中的名称。其中type = = 1
Example.
id | name | cid |cnames
1 | Joe | {10,20} |{aname,bname}
请告诉我这样做的有效方法是什么。 提前致谢。
答案 0 :(得分:1)
试试这个 对于版本< 9.0
SELECT A.id, A.name,
array_agg(b.cid) cids,array_agg(B.name) cnames
FROM Table1 A
JOIN
(
SELECT * FROM Table2 ORDER BY cid
)
B ON B.cid = ANY(A.cids)
WHERE type <> 1
GROUP BY A.id, A.name;
(以下版本适用于版本9 +)
SELECT A.id, A.name,
array_agg(b.cid order by b.cid) cids,
array_agg(B.name ORDER BY B.name) cnames
FROM Table1 A
JOIN Table2 B ON B.cid = ANY(A.cids)
WHERE type <> 1
GROUP BY A.id, A.name