【问题标题】:How to compare multiple column with multiple field array in Select query?如何在选择查询中将多列与多字段数组进行比较?
【发布时间】:2017-06-13 21:36:56
【问题描述】:

我在 API 服务器上创建查询时遇到了一些困难,我只想用修改后的曲目数据进行响应。我有 tracks 表,其中很少有这样的列。

tracks(id, audio_fingerprint, name, creation_date, modified_date)

现在我只想要在上次获取时间戳后更新的曲目(音频指纹数组和上次获取的时间戳作为 API 请求参数传递)。

SELECT * from tracks WHERE (audio_fingerprint, modified_date) IN (Array(audioFingerprint, > lastFetchedTimestamp));

(^^ 是无效查询,仅用于理解)。

谢谢

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    示例数据:

    create table tracks (audio_fingerprint text, modified_date date);
    insert into tracks values
        ('a', '2017-01-10'),
        ('b', '2017-01-10'),
        ('a', '2017-02-10'),
        ('b', '2017-02-10'),
        ('c', '2017-02-01');
    

    将您的参数放在with 查询中并将其与您的表连接:

    with given_values (fingerprint, last_fetched) as (
    values
        ('a', '2017-01-01'::date),
        ('b', '2017-02-01')
    )
    
    select * 
    from tracks t
    join given_values v
    on t.audio_fingerprint = v.fingerprint
    and t.modified_date > v.last_fetched;
    
     audio_fingerprint | modified_date | fingerprint | last_fetched 
    -------------------+---------------+-------------+--------------
     a                 | 2017-01-10    | a           | 2017-01-01
     a                 | 2017-02-10    | a           | 2017-01-01
     b                 | 2017-02-10    | b           | 2017-02-01
    (3 rows)
    

    您也可以使用派生表来代替 CTE:

    select * 
    from tracks t
    join (
        values
            ('a', '2017-01-01'::date),
            ('b', '2017-02-01')
        ) v(fingerprint, last_fetched)
    on t.audio_fingerprint = v.fingerprint
    and t.modified_date > v.last_fetched;
    

    【讨论】:

    • 它在 psql 中工作,但仍然不知道如何将 audio_fingerprint 和 modified_date 数据列表从 java 设置为 psql 语句。检查一下...
    • WITH (CTE) 与 jpa 本机查询一起使用,在 with 处给出令牌错误。我有很多依赖表都在轨道表上,这些数据也需要加载轨道数据。知道如何管理它吗?
    • 这里是问题的详细信息:Getting NoViableAltException: unexpected token: WITH with JPA - stackoverflow.com/questions/44567017/…
    • JPA does not support sub-selects/derived table in the FROM clause (正如我在 SO 回复中得到的那样),我有大约 5-7 个具有多级依赖关系的依赖表。有什么好的替代品吗?
    • 使用Native query 我们可以解决这个问题,但是我需要为每个实体、字段和它的依赖实体使用SqlResultSetMapping。对于以后的更改,有点冗长和复杂。
    【解决方案2】:

    也许LEAD or LAG可以帮到你?

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 2021-04-14
      • 2020-07-10
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多