小编典典

同一张表上的多个JOIN视图

sql

我有这个数据库存储传感器采集数据,
采集(acq)来自不同控制单元(cu)的固定间隔(日期时间)
每个采集在数据表中存储了许多不同的度量

acq
    id  
    datetime 
    id_cu

data          
    id        
    id_acq  
    id_meas
    value

我需要这种观点:

+---------------------+------+----+-----+
|      datetime       |  v1  | v2 |  v3 |
+---------------------+------+----+-----+
| 2010-09-13 00:05:00 | 40.9 |  1 | 0.3 |
| 2010-09-13 00:10:00 | 41.0 |  2 | 0.3 |
| 2010-09-13 00:15:00 | 41.1 |  4 | 0.3 |
+---------------------+------+----+-----+

作为:

  • v1是data.value(例如湿度),其中
    acq.id_cu = 1 AND data.id_meas = 100

  • v2是data.value(例如计数器),其中
    acq.id_cu = 2 AND data.id_meas = 200

  • v3是data.value(例如温度),其中
    acq.id_cu = 3 AND data.id_meas = 300

依此类推,用户最多可以选择数十种组合

我结束了此查询,但与将要生产的数据相比,它永久占用的数据量很少

SELECT a1.datetime, d1.value, d2.value, d3.value
FROM
    acq a1, data d1
    JOIN acq a2, data d2
        ON a2.id=d2.id_acq AND a2.datetime=a1.datetime
    JOIN acq a3, data d3
        ON a3.id=d3.id_acq AND a3.datetime=a1.datetime
WHERE a1.id=d1.id_acq
    AND a1.id_cu=1 AND d1.id_meas=100
    AND a2.id_cu=2 AND d2.id_meas=200
    AND a3.id_cu=3 AND d3.id_meas=300

我想这将是更快的方法,可以分别为每个a1.id_centr=x AND d1.id_meas=y条件获取数据,然后以我想要的方式打印应用程序中列出的数据。

实现这一目标的最佳(正确)方法是什么?

编辑:假设不缺乏收购我的意思是运行此:

SELECT datetime, value
FROM acq, data
WHERE acq.id=data.id_acq
    AND (
        id_cu=1 AND id_meas=100
        OR id_cu=2 AND id_meas=200
        OR id_cu=3 AND id_meas=300
    )
ORDER BY id_cu, id_meas

由id_cu / id_meas进行的拆分结果会更改,并使用编程语言(如python + numpy)并排显示结果,这是几分之一秒还是……分钟?


阅读 193

收藏
2021-04-14

共1个答案

小编典典

假设DATETIME和data.id_acq以及cu和id_meas都有索引,则可以尝试使用带有伪列占位符和kludgey MAX()的UNION查询。如果您的data.values不是负数,这应该可以工作(如果是,则可以选择一个非常大的负数而不是零作为虚拟占位符值,该数字远远超出了可能的范围):

    select FOO.datetime, max(FOO.v1), max(FOO.v2), max(FOO.v3)
    from
     (

     select acq.datetime, data.value as v1,0 as v2, 0 as v3
     from acq inner join data on acq.id = data.id_acq
     where acq.id_cu=1 and data.id_meas=100

     UNION

    select acq.datetime, 0 as v1, data.value as v2, 0 as v3
    from acq inner join data on acq.id = data.id_acq
    where acq.id_cu=2 and data.id_meas=200

    UNION

    select acq.datetime, 0 as v1, 0 v2, data.value as v3
    from acq inner join data on acq.id = data.id_acq
    where acq.id_cu=3 and data.id_meas=300
    ) as FOO
    group by FOO.datetime
2021-04-14