如何让SQLite Trigger将对象的JSON数组转换为新记录?

new9mtju  于 2023-06-23  发布在  SQLite
关注(0)|答案(1)|浏览(151)

我尝试在SQLite中创建一个触发器(BEFORE或AFTER INSERT),它接受这个新行:

** events table **
id   timeslots
1    [{start: 2023, end: 2024 }, { start: 2025, end: 2025 }, ...]

并保存到另一个表中:

** timeslots table **
id   end   start
1    2023  2024
1    2024  2025
1    ...   ...

此时,我的不工作触发器是:

CREATE TRIGGER IF NOT EXISTS insert_timeslots
  AFTER INSERT ON events
  BEGIN
    INSERT INTO timeslots (id, start, end)
    SELECT 
      json_extract(t.value, '$.id'),
      json_extract(t.value, '$.start'),
      json_extract(t.value, '$.end'),
    FROM json_each(NEW.timeslots) AS t;
END;`

我启动了一个DBFiddle来帮助调试。
有线索吗?谢谢

3mpgtkmj

3mpgtkmj1#

id不是json数组的一部分:

CREATE TRIGGER IF NOT EXISTS insert_timeslots AFTER INSERT ON events
BEGIN
  INSERT INTO timeslots (id, start, end)
  SELECT NEW.id,
         json_extract(t.value, '$.start'),
         json_extract(t.value, '$.end')
  FROM json_each(NEW.timeslots) AS t;
END;

参见demo

相关问题