我有这个数据库存储传感器采集数据,
采购(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 |
+---------------------+------+----+-----+
AS:
v1是data.value(例如湿度)
WHERE acq.id_cu = 1 AND data.id_meas = 100
v2是data.value(例如计数器)
WHERE acq.id_cu = 2 AND data.id_meas = 200
v3是data.value(例如温度)
WHERE 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)并排显示结果的分割结果是几秒钟与......分钟的关系?
答案 0 :(得分:2)
*假设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
答案 1 :(得分:1)
你的JOINS
有点令人困惑(因为你在暗示中混合显式);试试这个:
SELECT a1.datetime, d1.value, d2.value, d3.value
FROM
acq a1
INNER JOIN data d1 ON a1.id=d1.id_acq
INNER JOIN acq a2 ON a2.datetime=a1.datetime
INNER JOIN data d2 ON a2.id=d2.id_acq
INNER JOIN acq a3 ON a3.datetime=a1.datetime
INNER JOIN data d3 ON a3.id=d3.id_acq
WHERE 1=1
AND a1.id_centr=1 AND d1.id_meas=100
AND a2.id_centr=2 AND d2.id_meas=200
AND a3.id_centr=3 AND d3.id_meas=300