SQLite关系INSERT与未知外键

时间:2017-06-16 12:02:46

标签: database vb.net sqlite query-performance

我在VB.NET应用程序中创建了一个SQLite数据库。它存储2个表中多个varName记录的时间序列数据:

  1. varNames

    CREATE TABLE IF NOT EXISTS varNames(
        id      INTEGER PRIMARY KEY,
        varName TEXT    UNIQUE
    );
    

    看起来像这样:

    ID   |  varName
    ---------------
    1    |  var1
    2    |  var2
    ...  |  ...
    
  2. varValues

    CREATE TABLE IF NOT EXISTS varValues(
        timestamp INTEGER,
        varValue  FLOAT,
        id        INTEGER,
        FOREIGN KEY(id) REFERENCES varNames(id) ON DELETE CASCADE
    );
    

    看起来像这样:

    timestamp  |  varValue  |  id
    ------------------------------
    1          |  1.0345    |  1
    4          |  3.5643    |  1
    1          |  7.7866    |  2
    3          |  4.5668    |  2
    ...        |  ....      | ...
    
  3. 第一个表格包含varName ID。第二个包含每个varName的值作为时间序列(每timestamp)。外键链接表。插入varNames看起来像这样:

    INSERT OR REPLACE INTO varNames (
        varName
    ) VALUES (
        @name
    );
    

    我将特定varName的值插入到第二个表中,如下所示:

    INSERT OR REPLACE INTO varValues (
        timestamp,
        varValue,
        id
    ) VALUES (
        @timestamp,
        @value,
        (SELECT id FROM varNames WHERE varName = @name)
    );
    

    在插入时,我不知道varName ID对应的varValues记录。这就是我使用的原因:

    (SELECT id FROM varNames WHERE varName = @name)
    
    与直接通过ID进行寻址相比,

    似乎很慢。如何将INSERT表现提升到第二个表格?

1 个答案:

答案 0 :(得分:1)

  

...将INSERT性能提升到第二个表中?

使用a transaction(最好合并多个INSERT):

BEGIN TRANSACTION;

INSERT OR REPLACE INTO varValues (
    timestamp,
    varValue,
    id
) VALUES (
    @timestamp,
    @value,
    (SELECT id FROM varNames WHERE varName = @name)
);

INSERT OR REPLACE INTO varValues (
    timestamp,
    varValue,
    id
) VALUES (
    @timestamp,
    @value,
    (SELECT id FROM varNames WHERE varName = @name)
);

etc. ...

END TRANSACTION;

Related