在数据库表中存储样本数组

时间:2018-04-23 08:58:31

标签: database sqlite database-schema

每一秒我从一个我想要存储在数据库中的信号中取100个样本以及一些有关测量的其他数据。

我能想到的唯一方法是创建100列来存储样本:

Measurement Table:                     

 -------------------------------------------------------------------
| id  |     Time  | Temp  | Sample1 | Sample2 | Sample3 ... Sample100   |
 -------------------------------------------------------------------
| 01  |  12:34:56 |  22.3 |    1    |    2    |    3    ...     4       |  
 -------------------------------------------------------------------
| 02  |  12:34:57 |  22.3 |    2    |    3    |    4    ...     5       |  
 -------------------------------------------------------------------
| 02  |  12:34:58 |  22.3 |    3    |    4    |    5    ...     6       |  
 -------------------------------------------------------------------

这种做法似乎不太理想。有没有更好的方法呢?如果我想在以后更改样本数量,该怎么办?

1 个答案:

答案 0 :(得分:1)

您的案例从1对N的关系中受益匪浅。您可能需要两个表:

create table measurement (
  id bigint primary key not null generated always as identity,
  time timestamp not null,
  temp double not null
);

create table sample (
  measurement_id bigint not null,
  sample_number int not null, -- 1, 2, 3, ... 100
  sample_value double,
  constraing fk1_sample_meas foreign key (measurement_id) 
    references measurement (id)
);

measurement上,您每秒只能插入1行。在sample上,您每秒插入100行,与单次测量相关(列measurement_id)。

将来,如果每秒需要更多样本,则可以在sample中插入更多行。该表自然接受每秒更多(或更少)的样本。不需要进行结构改变。

一个注意事项:在每次测量时,您将插入101行(1个测量值+ 100个样本)。确保使用交易插入它们。否则,在系统不稳定的情况下,您可能会得到不完整的测量结果。