首页 > 解决方案 > 如何在 where 查询中使用 postgres 数组?

问题描述

postgreSQL 中的一个表有一列数据类型为 text[]

TableA:
id              uuid
tableb_ids      text[]

TableB:
id              uuid
name            text

现在我需要编写如下查询:

select * from tableB where id in (select tableb_ids from tableA where id ="xxxx-xxxx-xxxx-xxxx")

我无法更改架构/表定义。即)我不能为tableA中的tableB的每个条目保留很多条目。TableA 是一个复杂的表。

标签: sqlpostgresqlpostgresql-9.5

解决方案


要在一个表中查找其记录 id 包含在其他表的数组中的记录,您可以加入这些表:

SELECT b.*
FROM tableb b
INNER JOIN tablea a
    ON b.id::TEXT = ANY(a.tableb_ids)
    AND a.id = 'xxxx-xxxx-xxxx-xxxx'

你可以这样做的另一种方法:

SELECT b.*
FROM tableb b
WHERE id IN (
    SELECT UNNEST(a.tableb_ids)
    FROM tablea a
    WHERE a.id = 'xxxx-xxxx-xxxx-xxxx'
) x
-- not sure if the aliases are needed in the subquery

推荐阅读