【问题标题】:How to make use of a postgres Array in where query?如何在 where 查询中使用 postgres 数组?
【发布时间】:2019-11-11 11:14:52
【问题描述】:

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 是一个复杂的表。

【问题讨论】:

  • 类似SELECT b.* FROM tableb b JOIN tablea a ON b.id = ANY(a.tableb_ids)
  • @404 当我尝试这种方式时,我得到ERROR: operator does not exist: uuid = text[]
  • b.id::TEXT = ANY(a.tableb_ids)
  • @Surya:一旦您对最初的问题有了答案,请不要扩展您的问题。而是提出一个新问题。
  • @404:您应该将其添加为答案,以便可以接受并且可以将问题标记为已解决

标签: sql postgresql postgresql-9.5


【解决方案1】:

要在一个表中查找其记录 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多