Replace values in array column with related values from another table

时间:2019-01-18 18:11:26

标签: sql arrays postgresql

In my database I have a table relations with a column relation_ids containing the IDs of users (user_id). This takes the form of an array with many IDs possible, e.g.:

{111,112,156,4465}

I have another table names containing information on users such as user_id, first_name, last_name etc.

I would like to create an SQL query to return all rows from relations with all columns, but append the array column relation_ids with first_name from the names table substituted for IDs.

Is it possible as some kind of subquery?

2 个答案:

答案 0 :(得分:0)

This will get you all the columns and rows from Relations with first_name appended from the Names table.

Select Relations.relation_ids, Names.user_id, Names.first_name From Relations
Inner Join Names On Relations.user_id=Names.user_id

答案 1 :(得分:0)

假设您要保留数组中的顺序-名字的顺序与原始relation_ids中ID的顺序相同。

我建议在unnest()WITH ORDINALITY表的关联子查询上使用ARRAY constructor,并加入names表,例如:

SELECT r.*
    , (ARRAY (
         SELECT n.first_name
         FROM   unnest(r.relation_ids) WITH ORDINALITY AS a(user_id, ord)
         JOIN   names n ON n.user_id = a.user_id
         ORDER  BY a.ord
         )
       ) AS first_names
FROM   relations r;

无论如何,此查询都会保留relations中的所有行。

需要注意的一些案例:
1. NULL中的relation_ids值(对于整个列)将转换为空数组。 (与源代码中的空数组相同。)
2. NULL 元素从数组中静默删除。

如果可能的话,您可能想定义所需的行为...

db <>提琴here

相关:

考虑了归一化的数据库设计: