高级别的我已经知道您不能在同一张表中插入新行,因此应该考虑使用SPROC。这是用例。我有一个第三方Web应用程序和这个MySQL数据库,因此我无法控制应用程序流程。提出了简化数据输入的请求。我所能控制的是数据库。该应用程序就像CRM一样,并具有一个contacts表,还有一个第二contact_relationships表,我可以在其中放置触发器。基本上,contact_relationships需要三个字段。联系人表中的两个contactID(INT)和诸如配偶,同级,外部家庭等)的Relationship_type varchar(45)。
这里的目标是在向contact_relationships表中添加新行(TRIGGER)时,我们还向SAME TABLE中写入第二行,该行会反转contactID并保留Relationship_type。这确保了从同一单个条目为其他联系人建立的记录关系。 (最好在应用程序中完成)。
我本来应该做一个愚蠢的简单操作,却一头雾水。我什至尝试了这种创造性的实现。
我创建了一个新的_temp表
CREATE TABLE `_temp` (
`id_temp` int(11) NOT NULL AUTO_INCREMENT,
`Contact_id` int(11) DEFAULT NULL,
`Relation_id` int(11) DEFAULT NULL,
`Relationship_Type` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id_temp`)
contact_relationships表上有两个触发器
#1
CREATE DEFINER=`root`@`localhost` TRIGGER `contact_relationships_BEFORE_INSERT` BEFORE INSERT ON `contact_relationships` FOR EACH ROW BEGIN
insert into _temp (Contact_id,Relation_id,Relationship_Type)
values(NEW.Contact_id,NEW.Relation_id,NEW.Relationship_Type);
END
#2
CREATE DEFINER=`root`@`localhost` TRIGGER `contact_relationships_AFTER_INSERT` AFTER INSERT ON `contact_relationships` FOR EACH ROW BEGIN
delete from _temp;
END
在_temp表上,我有此触发器
CREATE DEFINER=`root`@`localhost` TRIGGER `_temp_AFTER_DELETE` AFTER DELETE ON `_temp` FOR EACH ROW BEGIN
#DO Sleep(2);
# Sleep commented out as it did not work and only delayed the error
insert into contact_relationships (Relation_id,Contact_id,Relationship_Type) values(OLD.Contact_id,OLD.Relation_id,OLD.Relationship_Type);
END
所以我在伪代码中的想法是这样的
When a row is inserted into the contact_relationships table write the inverted row to a temp table as I can not write it to the **same table from inside the trigger**.
AFTER the triggered inserted row is complete lets delete the row in the temp table so we can create a DELETE trigger on that other table to write the desired row into the contact_relationship.
At this stage I believe the TRIGGER and TRANSACTIONS on the contact_relationships table are DONE
On the temp Table a trigger and transaction firing AFTER any contact_relationships transactions
结果令人发疯,并且无论内部还是外部,结果始终相同。我已经尝试过具有创造力的功能,并且存储过程都具有相同的恶化结果。
Contact Relationships : Add New
Can't update table 'contact_relationships' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Query:
insert into `Contact_Relationships` set `Contact_id`='2', `Relation_id`='3', `Relationship_Type`='Extended Family'
我完全不知道该如何实现这一目标-任何人都有办法实现这一目标?
答案 0 :(得分:0)
dsoden。
我要做的是:
在触发器定义中,您可以获取所插入关系的“ inserted_id” (您可以通过 LAST_INSERT_ID()获得它>)。
一旦有了它,就可以从该记录中选择TEMP变量:
SELECT `Contact_id`,`Relation_id`,`Relationship_Type` INTO @cont_id, @rel_id, @rel_type
FROM contact_relationships
WHERE id = LAST_INSERT_ID()
然后使用相同的关系类型以相反的顺序插入新关系:
INSERT INTO contact_relationships (`Contact_id`,`Relation_id`,`Relationship_Type`) VALUES ( @rel_id, @cont_id, @rel_type);
如果这是您的目标。
类似的东西:
当安妮与约翰兄弟姐妹之间的关系插入时, 插入约翰,安妮,兄弟姐妹的关系