sql - 如何在 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 是一个复杂的表。
解决方案
要在一个表中查找其记录 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
推荐阅读
- c - malloc(sizeof(ptr)) 和 malloc(sizeof(ptr*)) 之间的区别?
- ruby-on-rails - Rails 6 gemfile.lock 删除,再次生成
- python-3.x - 我尝试安装 urlparse4 时出错
- visual-studio - Visual Studio 需要 D 上的空间:
- haskell - Function that shows all lists, which are ascending
- keras - 使用 keras 评估多任务学习的模型结果
- networking - 为什么 NAT 会导致在家庭网络上运行的服务器出现问题?
- python - 从现有列生成新数据框
- python - 极坐标中数据点的Python数值积分
- c# - 显示每月复利值的方法?