postgresql - 通过二维数组列的第二个维度中的值查询表

标签 postgresql

我有什么

我有一个定义如下的表:


CREATE TABLE "Highlights"
(
  id uuid,
  chunks numeric[][]
)

我需要做什么

我需要使用以下谓词查询表中的数据:

... WHERE id = 'some uuid' and chunks[????????][1] > 10 chunks[????????][3] < 20

为了扫描数组第一维中的所有项目,我应该放什么而不是 [?????????]

注意事项

我不确定 chunks[][1] 是否接近我需要的东西。

我只需要测试一行,看它的 chunks 列是否包含一个二维数组,它的任何元组中都有一些特定的值。

最佳答案

可能有更好的选择,但这可能会做 - 你只需遍历每个数组的第一个维度并测试你的条件:

select *
from highlights as h
where
    exists (
        select
        from generate_series(1, array_length(h.chunks, 1)) as tt(i)
        where
            -- your condition goes here
            h.chunks[tt.i][1] > 10 and h.chunks[tt.i][3] < 20
    )

db<>fiddle demo

update 正如@arie-r 指出的那样,最好使用 generate_subscripts 功能:

select *
from highlights as h
where
    exists (
        select *
        from generate_subscripts(h.chunks, 1) as tt(i)
        where
            h.chunks[tt.i][3] = 6
    )

db<>fiddle demo

关于postgresql - 通过二维数组列的第二个维度中的值查询表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643847/

相关文章:

sql - 如何 md5 所有列而不考虑类型

sql - Postgres 在 json 中查找唯一值

sql - 为什么 Postgres 中没有 "SELECT foo.* ... GROUP BY foo.id"?

database - 从无限流中选择 10% 的随机数

sql - 如何使空值在 SQL 中被视为 MAX?

postgresql - 我不知道 Postgresql 如何在我的 mac 上创建用户

mysql - DISTINCT 和 LAG 窗函数

sql - 修改 SQL 语句以追加表中的列

postgresql - 为什么 postgres 官方 docker repo 不在构建时启动 db 服务?

postgresql - 如何正确分组 Postgres 数据