我需要更新table_1中记录的主ID值,同时更新引用该ID值的外键。在下面的sql中,我已经包含引用table_1的所有表,但并非所有这些表都引用该特定记录。 我正在使用下面的SQL:
UPDATE table_1 T1,
table_2 T2,
table_3 T3,
table_4 T4,
table_5 T5,
table_6 T6,
table_7 T7
SET T1.EMI_ID = 15678,
T2.AKN_EMI_FK = 15678,
T3.EXP_EMI_FK = 15678,
T4.HDR_EMI_FK = 15678,
T5.LSU_EMI_FK = 15678,
T6.MUT_EMI_FK = 15678,
T7.IMG_EMI_FK = 15678
WHERE T1.EMI_ID = 77777718765 AND
T2.AKN_EMI_FK = T1.EMI_ID AND
T3.EXP_EMI_FK = T1.EMI_ID AND
T4.HDR_EMI_FK = T1.EMI_ID AND
T5.LSU_EMI_FK = T1.EMI_ID AND
T6.MUT_EMI_FK = T1.EMI_ID AND
T7.IMG_EMI_FK = T1.EMI_ID;
它似乎不起作用,我相信这可能是因为在某些表中,记录ID不作为外键存在。
有更好的方法吗?
答案 0 :(得分:1)
是的,通过使用外键UPDATE约束: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
示例:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB;