使用触发器 SQlite 根据另一个 table 的输入增加特定行的值
Increase the value of a specific row depending on the input of another table using triggers SQlite
我的问题是:
每当我在名为 A 的 table 中插入一个单词时,table B 必须在 ID 与输入单词中的字母数相同的行中将其值更新 +1。
这必须使用触发器来完成。
例如,如果我在 table A 上输入单词 ("macaroni"),table 的 B 列中 ID 为 (8) 的值必须增加 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 的新手,所以非常感谢您帮助解决这个问题!
编辑:Table A 包含一列(单词),而 Table B 包含两列,id 和 value。所以每次我们有一个以前没有添加的字长时,我们可能必须输入 id 的值。
假设 table 定义如
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;
如果长度 table 中不存在给定长度的新行,它首先添加一个新行,然后将相应行的计数增加 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
我假设 table B
中的 ID
列是主键。
如果 table B 不包含每个可能长度的行,则可以在触发器内部使用 UPSERT
14=] 将被插入到 B 中,否则现有行将递增:
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。
我的问题是: 每当我在名为 A 的 table 中插入一个单词时,table B 必须在 ID 与输入单词中的字母数相同的行中将其值更新 +1。 这必须使用触发器来完成。 例如,如果我在 table A 上输入单词 ("macaroni"),table 的 B 列中 ID 为 (8) 的值必须增加 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 的新手,所以非常感谢您帮助解决这个问题!
编辑:Table A 包含一列(单词),而 Table B 包含两列,id 和 value。所以每次我们有一个以前没有添加的字长时,我们可能必须输入 id 的值。
假设 table 定义如
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;
如果长度 table 中不存在给定长度的新行,它首先添加一个新行,然后将相应行的计数增加 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
我假设 table B
中的 ID
列是主键。
如果 table B 不包含每个可能长度的行,则可以在触发器内部使用 UPSERT
14=] 将被插入到 B 中,否则现有行将递增:
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。