如何在 where 查询中使用 postgres 数组?
How to make use of a postgres Array in where query?
postgreSQL 中的一个 table 有一列数据类型为 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")
我无法更改 schema/table 定义。
即)我不能为 tableA 中的每个 tableB 条目保留很多条目。 TableA 是一个复杂的 table.
要在一个 table 中查找其记录 ID 包含在另一个 table 的数组中的记录,您可以加入 tables:
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
postgreSQL 中的一个 table 有一列数据类型为 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")
我无法更改 schema/table 定义。 即)我不能为 tableA 中的每个 tableB 条目保留很多条目。 TableA 是一个复杂的 table.
要在一个 table 中查找其记录 ID 包含在另一个 table 的数组中的记录,您可以加入 tables:
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