您将如何尝试插入并同时更新或删除现有记录?
假设我有一张桌子:
CREATE TABLE IF NOT EXISTS `components` (
`id` int NOT NULL AUTO_INCREMENT,
`component` int DEFAULT NULL,
`x` int DEFAULT NULL,
`y` int DEFAULT NULL,
`parent_id` int DEFAULT NOT NULL,
`state` char(3) DEFAULT NULL,
PRIMARY KEY (`id`)
);
我在mysql中知道一个简单的upsert语句
INSERT INTO components (id, component, x, y, parent_id) VALUES
(1, 2, 0, 0, 1),
(2, 1, 0, 1, 1),
(3, 7, 1, 1, 2)
ON DUPLICATE KEY UPDATE
component = values(component),
x = values(x),
y = values(y);
现在我还想在缺少id的情况下删除组件。任何想法如何实现这一点,还是我应该写一个程序?
不,忘了这个。我不认为这是可能的(我不想让自己变得复杂)。我想我会先删除所有旧记录并将所有旧记录插入新值......这个解决方案并不好,但如果有其他人有建议,请随时给我一些选择。触发器也不起作用:
delimiter |
CREATE TRIGGER update_state BEFORE UPDATE ON components
FOR EACH ROW BEGIN
IF new.ID IS NULL THEN # if id is missing set to old
SET NEW.state = 'old';
else
SET NEW.state = 'new'; # if id is present set to new
END IF;
END;
|
delimiter ;
delimiter |
CREATE TRIGGER insert_state BEFORE INSERT ON components
FOR EACH ROW BEGIN
SET NEW.state = 'new';
END;
|
delimiter ;
我是如何将这三个查询提交给一个procodure的?我需要给程序提供一个对象数组(也许我可以用json / xml作为参数传递吗?)
UPDATE components SET state = 'old' WHERE parent_id = 2;
INSERT INTO components (id, component, x, y, parent_id) VALUES
(1, 1, 0, 0, 2),
(2, 5, 1, 0, 2),
(3, 6, 0, 1, 2),
(4, 7, 1, 1, 2)
ON DUPLICATE KEY UPDATE
component = values(component)
DELETE FROM components WHERE parent_id = 2 and state = 'old';