Mysql
MySQL 觸發器查詢未按預期刪除
我有一個測試數據庫,如下所示。如果日期在 tbl1 中更新,我希望觸發一個觸發器,從 tbl2 中刪除所有條目,其中 tbl1.host = tbl2.host2 AND tbl1.date = NEW.date。
這是盡可能接近的,但它不起作用。預先感謝您!
DELETE tbl2.* FROM tbl1,tbl2 WHERE (tbl1.host = tbl2.host AND date = NEW.date)
樣本數據
CREATE TABLE IF NOT EXISTS tbl1 ( host varchar(10) NOT NULL, package1 varchar(10) NOT NULL, date datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; DELIMITER $$ CREATE TRIGGER `Before_Insert` BEFORE INSERT ON `tbl1` FOR EACH ROW DELETE tbl2.* FROM tbl1,tbl2 WHERE (tbl1.host = tbl2.host AND date = NEW.date) -- Should be tbl2.host2 (no host field in tbl2) EDIT. $$ DELIMITER ; CREATE TABLE IF NOT EXISTS `tbl2` ( `packageid` tinyint(10) NOT NULL, `package2` varchar(10) NOT NULL, `host2` varchar(10) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; INSERT INTO `tbl2` (`packageid`, `package2`, `host2`) VALUES (1, 'a', '1'), (2, 'b', '2'), (3, 'c', '3'), (4, 'd', '4'); ALTER TABLE `tbl1` ADD PRIMARY KEY (`host`,`package1`) USING BTREE; ALTER TABLE `tbl2` ADD PRIMARY KEY (`packageid`); ALTER TABLE `tbl2` MODIFY `packageid` tinyint(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
你想要的是(類似於):
DELIMITER $$ CREATE TRIGGER `Before_Insert_tbl1` BEFORE INSERT ON `tbl1` FOR EACH ROW BEGIN DELETE FROM tbl2 WHERE (NEW.host = tbl2.host2); -- note not tbl1.host - out of scope! -- AND date = NEW.date) -- not sure what the date logic is here. AFAICS -- it's superfluous. Could be NEW.date = DATE(NOW());? -- i.e. delete it if it's today's record, otherwise don't? END $$ DELIMITER ;
您的問題是 tbl1.host 在
WHERE
超出範圍的子句中。引用新的NEW
tbl1 記錄 - 不需要表引用。另外,正如我所指出的,“日期”令人困惑——它什麼都不做——tbl1.date(插入的記錄)將自動等於
NEW
.date。最後,您似乎犯了一個錯誤TRIGGER
- 沒有 tbl2.host (應該是“host2”?)。如果我的邏輯不是完美無缺的,我已經對其進行了編輯,以便其他人更容易:-)。
AND date = NEW.date)
–>
AND tbl1.date = NEW.date)