是否可以在SQLite触发器中更新多行?请参阅下面的触发器。
CREATE TRIGGER "saved_tiles_reference"
BEFORE DELETE ON favourites
FOR EACH ROW
BEGIN
UPDATE saved_tiles SET reference_count = reference_count - 1 WHERE id = (select tile from favourite_tiles where favourite = OLD.id);
DELETE FROM favourite_tiles WHERE id = OLD.id;
END;
如您所见,我希望将saved_tiles上的引用计数减少1.我想要更新的saved_tiles是使用where子句中的select语句定义的。
此触发器有效,但仅适用于它遇到的第一个条目。
修改
saved_tiles
属于其父favourites
,并且他们通过表favourite_tiles
加入。这是我的数据库结构
-- ----------------------------
-- Table structure for favourite_tiles
-- ----------------------------
DROP TABLE IF EXISTS "favourite_tiles";
CREATE TABLE "favourite_tiles" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"favourite" integer NOT NULL,
"tile" integer NOT NULL
CONSTRAINT "fk_favourite" FOREIGN KEY ("favourite") REFERENCES "favourites" ("id"),
CONSTRAINT "fk_tiles" FOREIGN KEY ("tile") REFERENCES "saved_tiles" ("id")
);
INSERT INTO "main".sqlite_sequence (name, seq) VALUES ("favourite_tiles", '2');
-- ----------------------------
-- Table structure for favourites
-- ----------------------------
DROP TABLE IF EXISTS "favourites";
CREATE TABLE "favourites" (
"id" integer NOT NULL,
PRIMARY KEY("id")
);
-- ----------------------------
-- Table structure for saved_tiles
-- ----------------------------
DROP TABLE IF EXISTS "saved_tiles";
CREATE TABLE "saved_tiles" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"reference_count" integer NOT NULL DEFAULT 0
);
INSERT INTO "main".sqlite_sequence (name, seq) VALUES ("saved_tiles", '1');
-- ----------------------------
-- Triggers structure for table favourite_tiles
-- ----------------------------
CREATE TRIGGER "increment_tile_reference"
BEFORE INSERT ON favourite_tiles
FOR EACH ROW
BEGIN
-- Type the SQL Here.
UPDATE saved_tiles SET reference_count = reference_count + 1 WHERE id = NEW.tile;
END;
-- ----------------------------
-- Triggers structure for table favourites
-- ----------------------------
CREATE TRIGGER "saved_tiles_reference"
BEFORE DELETE ON favourites
FOR EACH ROW
BEGIN
-- Type the SQL Here.
UPDATE saved_tiles SET reference_count = reference_count - 1 WHERE id = (select tile from favourite_tiles where favourite = OLD.id);
DELETE FROM favourite_tiles WHERE id = OLD.id;
END;
答案 0 :(得分:1)
不幸的是我解决了它。
我没有使用id = (select....
,而是在修改后的触发器中使用id IN (select ...
,如下所示。
CREATE TRIGGER "saved_tiles_reference"
BEFORE DELETE ON favourites
FOR EACH ROW
BEGIN
UPDATE saved_tiles SET reference_count = reference_count - 1 WHERE id IN (select tile from favourite_tiles where favourite = OLD.id);
DELETE FROM favourite_tiles WHERE favourite = OLD.id;
END;