直到大约5分钟前,我甚至不知道你得到的类型VARCHAR也是一个数组。我如何加入这些表格:
PEOPLE
ID | PERSON | GROUPS
1 | John | {ONE,TWO}
2 | Jack | {TWO}
3 | Jill | {ONE,TWO,THREE}
4 | Jim | {TWO,THREE}
GROUPS
ID | TITLE
ONE | First
TWO | Second
THREE | Third
我想结束这样的事情:
ID | PERSON | GROUP
1 | John | ONE
1 | John | TWO
2 | Jack | TWO
3 | Jill | ONE
3 | Jill | TWO
3 | Jill | THREE
4 | Jim | TWO
4 | Jim | THREE
如何在一个查询中获得此权限?
答案 0 :(得分:6)
unnest
,您可以使用带有数组成员资格测试的简单连接:
SELECT people."ID", people."PERSON", groups."ID"
FROM people
INNER JOIN groups ON groups."ID" = ANY (people."GROUPS")
ORDER BY people."ID", groups."ID";
请参阅:http://sqlfiddle.com/#!12/5fa34/7
(奇怪的上层框是因为我无法解决修复SQLFiddle不一致的标识符引用问题。它引用了列名而不是表名。)
您甚至可以在people.GROUPS
上使用GIN索引并获得索引连接。 GIN索引的构建并不便宜,而且更新成本很高,所以你只需要在真正需要的时候这样做,但它很有用。请参阅阵列索引手册。例如:
CREATE INDEX people_groups_gin_idx ON people USING GIN("GROUPS");
SELECT people."ID", people."PERSON", groups."ID"
FROM people
INNER JOIN groups ON ARRAY[groups."ID"] @> people."GROUPS"
ORDER BY people."ID", groups."ID";
答案 1 :(得分:2)
对于那个特定的查询,有一个使用unnest()
的语法技巧,当它成为select语句的一部分时,允许将一行扩展为多行:
select id, person, unnest(groups) as grp
from people
我猜你实际上想要第一,第二,第三,而不是一,二,三。您可以这样加入:
with unnested_people as (
select id, person, unnest(groups) as grp
from people
)
select id, person, title
from unnested_people
join groups on groups.id = unseated_people.grp