【问题标题】:Increase the value of a specific row depending on the input of another table using triggers SQlite使用触发器 SQlite 根据另一个表的输入增加特定行的值
【发布时间】:2021-07-04 01:34:55
【问题描述】:

我的问题是这样的: 每当我在名为 A 的表中插入一个单词时,表 B 必须在 ID 与输入单词中的字母数相同的行中将其值更新 +1。 这必须通过触发器来完成。 例如,如果我在 A 表上输入单词(“macaroni”),则表 B 的 ID 为(8)的名为 value 的列必须增加 1。

例如

ID-值

8 - 1

CREATE TRIGGER update_value
after insert on A
for each ROW
BEGIN
 SELECT id FROM B LIMIT CHAR_LENGTH(A),1; 
 update B set value = value + 1;
end

当然,它不起作用,因为我对 SQLite 还很陌生,所以非常感谢您对如何解决这个问题的帮助!

编辑:表 A 包含一列(单词),而表 B 包含两列,即 id 和 value。因此,每次我们有一个以前没有添加的字长时,我们可能都必须输入 id 的值。

【问题讨论】:

  • 发布表的定义。表 B 是否包含具有所有可能长度的行?
  • @forpas 刚刚编辑了它!

标签: sql database sqlite triggers


【解决方案1】:

我假设表B 中的列ID 是主键。
如果表 B 不包含每个可能长度的行,您可以在触发器中使用 UPSERT,这样如果在 A 中插入具有新长度的单词,则在 B 中插入带有 value = 1 的新行,否则现有行将递增:

CREATE TRIGGER update_value AFTER INSERT ON A
BEGIN
  INSERT INTO B(id, value)
  SELECT LENGTH(NEW.word), 1
  ON CONFLICT(id) DO UPDATE
  SET value = value + 1;
END

请参阅demo

【讨论】:

  • 非常感谢!演示真的很有帮助!我想知道如果我会使用与您描述的方法相同(几乎)的方法,以便在删除时添加一个触发器。
  • @ReactingInnocent 检查这个:dbfiddle.uk/…
【解决方案2】:

假设表定义像

create table wordlens(id integer primary key, count integer);
create table words(id integer primary key, word text);

类似这样的触发器:

create trigger update_value after insert on words
begin
  insert or ignore into wordlens values (length(new.word), 0);
  update wordlens set count = count + 1 where id = length(new.word);
end;

首先,如果长度表中尚不存在给定长度的新行,它会添加一个新行,然后将相应行的计数增加 1。

示例用法:

sqlite> insert into words(word) values ('macaroni');
sqlite> select * from wordlens;
id  count
--  -----
8   1
sqlite> insert into words(word) values ('abcdefgh');
sqlite> select * from wordlens;
id  count
--  -----
8   2    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多