如何使用外键将行插入到 table 中,外键会自动递增,而无需对父 table 进行多次查询

how to insert rows to a table with foreign key which is auto incremented without multiple queries to the parent table

我有一个“指标”父级 table 和一个“键值”子级 table。

metrics 中的每一行都可以有关联的键值存储在“键值”table(键值的数量不受限制,可以是 0 或更多)

指标行 ID 自动递增,时间戳由 sqlite 生成,(因为在同一实例中允许多个指标)

例如我想到了这样的架构:

CREATE TABLE metrics (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        created_at TIMESTAMP NOT NULL DEFAULT (datetime('now','localtime')),
        name TEXT NOT NULL,
    );

CREATE TABLE keyvalues(
    key TEXT,
    value TEXT,
    metric_id INTEGER,
    CONSTRAINT fk_keyval
      FOREIGN KEY(metric_id) 
      REFERENCES metrics(id)
      ON DELETE CASCADE
);

metric id 主键是 auto-incrementedtimestamp 是由 sqlite 生成的,我不确定如何向两个指标插入行 table 和关联的 keyvalues table 同时。

我的内部 API 看起来像(伪代码):

Metric {
  name: String,
  keyvals: Map<String,String>
}


func count_metric(metric: Metric) {
  sqlite.execute("insert into metrics(name) value(metric.name)");
// now how to go about inserting to the `keyvalues` table?
   foreach (key,value) in metric.keyvals {
       sqlite.execute("insert into keyvalues(key,value,metric_id) values(?,?,?)" , key , value , "rowid") // how do I get the row id efficiantly and ensure correctness if multiple inserts occur conccurently?
   }

}

我是否必须先插入指标 table,查询最后一行 ID,然后将适当的条目插入键值 table?

您可以使用 last_insert_rowid():

insert into metrics(name) values(?);
insert into keyvalues(key, value, metric_id) values(?, ?, last_insert_rowid());