2

直到大约 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

我如何在一个查询中做到这一点?

4

2 回答 2

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

(The weird upper-casing is because I couldn't be bothered fixing SQLFiddle's inconsistent identifier quoting. It quotes column names but not table names.)

You can even use a GIN index on people.GROUPS and get an indexed join. The GIN index isn't cheap to build and is expensive to update so you'll only want to do that when you really need to, but it's useful. See the manual on array indexes. eg:

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";
于 2013-06-12T12:46:40.980 回答
2

对于该特定查询,有一个语法技巧 using unnest(),当它是 select 语句的一部分时,它允许将单行扩展为多行:

select id, person, unnest(groups) as grp
from people

但是,我猜您实际上希望出现 First、Second、Third 而不是一个、两个或三个。你可以这样加入:

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
于 2013-06-12T08:42:02.583 回答