目前,我将一些模拟的结果存储在具有以下结构的SQLite3
表中
Table: radiation
id, timestamp, surface_total_shortwave, cell_id
1 , 2010-01-01 09:00:00, 3.5, 1
2 , 2010-01-01 10:00:00, 2.5, 1
3 , 2010-01-01 11:00:00, 10.0, 1
4 , 2010-01-01 12:00:00, 6.5, 1
5 , 2010-01-01 09:00:00, 2.5, 2
6 , 2010-01-01 10:00:00, 1.5, 2
7 , 2010-01-01 11:00:00, 10.0, 2
8 , 2010-01-01 12:00:00, 5.5, 2
.., ..................., ....., .
100 , 2010-01-01 09:00:00, 1.5, 34
101 , 2010-01-01 10:00:00, 1.5, 34
102 , 2010-01-01 11:00:00, 4.0, 34
103 , 2010-01-01 12:00:00, 3.5, 34
104 , 2010-01-01 09:00:00, 1.5, 45
105 , 2010-01-01 10:00:00, 2.5, 45
106 , 2010-01-01 11:00:00, 7.0, 45
107 , 2010-01-01 12:00:00, 2.5, 45
.., ..................., ....., .
实际创建声明:
CREATE TABLE cfd(id INTEGER PRIMARY KEY, time DATETIME, u, cell_id integer)
对于每个cell_id
,我都有相同数量的时间戳。
我需要减去(cell1 - cell2)组合列表的时间序列,将其分配给cell1并创建一个用户可以查询的view
。
例如:
cell1 = 1 and cell2 = 34
cell1 = 2 and cell2 = 45 (duplicates are possible for cell2)
对于一个单细胞组合,我做
create view ds as
select time1, (sts1 - sts2) as sts, cell_id from
(select time as time1, cell_id, surface_total_shortwave as sts1 from radiation where cell_id = 1)
inner join
(select time as time2, surface_total_shortwave as sts2 from radiation where cell_id = 34)
on time1 = time2
当我有像
这样的映射时,如何扩展此查询(cell1, cell2)
(1, 34)
(2, 45)
(..., ...)
结果表,假设映射仅针对上面的2个单元格(1 - > 34)和(2 - > 45)将是以下
Table: radiation
id, timestamp, sts, cell_id
1 , 2010-01-01 09:00:00, 2.0, 1
2 , 2010-01-01 10:00:00, 1.0, 1
3 , 2010-01-01 11:00:00, 6.0, 1
4 , 2010-01-01 12:00:00, 3.0, 1
5 , 2010-01-01 09:00:00, 1.0, 2
6 , 2010-01-01 10:00:00, -1.0, 2
7 , 2010-01-01 11:00:00, 3.0, 2
8 , 2010-01-01 12:00:00, 3.0, 2
EDIT 似乎可能的解决方案是创建一个临时表来存储映射
Table: mapping
idx, cell1, cell2
1, 1 , 34
2, 2 , 45
.., ..., ...
现在我可以用这种方式重写查询
select time1, (sts1 - sts2) as sts, cell1_id, cell2_id from
(select time as time1, cell_id as cell1_id, surface_total_shortwave as sts1 from radiation where cell_id in (1, 2))
inner join
(select time as time2, cell_id as cell2_id, surface_total_shortwave as sts2 from radiation where cell_id in (34, 45))
on time1 = time2 and cell1_id = (select mapping.cell1 from mapping where mapping.cell2 = cell2_id)
答案 0 :(得分:1)
只需连接多个查询:
CREATE VIEW ds AS
SELECT time,
r1.surface_total_shortwave - r2.surface_total_shortwave AS sts,
r1.cell_id
FROM radiation AS r1
JOIN radiation AS r2 USING (time)
WHERE (r1.cell_id, r2.cell_id) = (1, 34)
UNION ALL
SELECT ...
...
WHERE (r1.cell_id, r2.cell_id) = (2, 45);
或者,对所有单元格比较使用单个查询:
CREATE VIEW ds AS
SELECT time,
r1.surface_total_shortwave - r2.surface_total_shortwave AS sts,
r1.cell_id
FROM radiation AS r1
JOIN radiation AS r2 USING (time)
WHERE (r1.cell_id, r2.cell_id) = (1, 34)
OR (r1.cell_id, r2.cell_id) = (2, 45);
(两个查询都需要适当的索引才能有效。哪一个更快取决于数据;你必须自己测量它。)
可以使用临时表进行映射,但只有在有更多映射的情况下才值得。