【问题标题】:SQL find rows with closest higher values than each value in specified set of valuesSQL 查找具有比指定值集中的每个值最接近的更高值的行
【发布时间】:2016-01-27 12:12:50
【问题描述】:

我在数据库中每 6 小时收集一次统计数据,每个数据都带有时间戳。然后我的代码中有时间戳数组。我需要从数据库中为我的时间戳数组中的每个值选择一个值,并且该行将具有比数组中最接近的时间戳。

为了说明: 数据表

Id   Timestamp   Value
1    1400000027  10
2    1400000035  15
3    1400000043  20
4    1400000044  21
5    1400000048  30
6    1400000060  35

该数组包含以下时间戳:

[1400000020, 1400000024, 1400000035, 1400000050]

我需要根据输入数组从数据库中获取的行是:

Id   Timestamp   Value
1    1400000027  10
1    1400000027  10
2    1400000035  15
6    1400000060  35

有没有一种简单的方法可以在一个查询中执行此操作?最好的解决方案是教义,因为我使用的是 Symfony 2 和 Doctrine。

【问题讨论】:

    标签: php sql postgresql symfony doctrine-orm


    【解决方案1】:

    说实话,对每个值执行单独的查询可能是最简单的:

    select t.*
    from table t
    where t.TimeStamp >= $timestamp
    order by TimeStamp
    limit 1;
    

    在TimeStamp 上有一个索引,这个查询应该很快。

    您可以在单个查询中执行此操作。我倾向于将值存储在表中(如有必要,您可以展开数组值)。在 Postgres 9.3 及更高版本中,您可以将其表述为横向连接:

    with timestamps as (
          select 1400000020 as ts union all
          select 1400000024 union all
          select 1400000035 union all
          select 1400000050
         )
    select t.*
    from timestamps cross join lateral
         (select
          from table t
          where t.timestamp >= timestamps.ts
          order by t.timestamp
          limit 1
         ) t;
    

    【讨论】:

    • 我之所以不对每一行进行查询,是因为输入数组中可能有大量的时间戳,会导致大量的查询。
    【解决方案2】:

    这通常在 PostgreSQL 中使用 DISTINCT ON 完成(如果您可以使用非标准 SQL)

    SELECT    DISTINCT ON (ts_min) t.*
    FROM      unnest(ARRAY[1400000020, 1400000024, 1400000035, 1400000050]) ts_min
    LEFT JOIN table_name t ON t.timestamp >= ts_min
    ORDER BY  ts_min, t.timestamp
    

    如果不能绑定数组,可以使用values构造:

    FROM      (VALUES (1400000020), (1400000024), (1400000035), (1400000050)) v(ts_min)
    

    相关解决方案:

    【讨论】:

      猜你喜欢
      • 2019-04-11
      • 2022-08-13
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多