将记录插入表时,MySql会自动更新第二个表

时间:2014-08-20 09:40:57

标签: mysql sql

当一行插入tableb时,如果没有任何存储过程或其他内容,如何使用tablea中的值自动更新第二个表tablea

例如,如果要在此处将一行插入到表格中,我希望使用tableb itemId tablea更新itemTempId中的所有行tableb中的1}}与tablea

中的{}相同

两个表都是MyIsam类型

插入表格之前

tablea

"id"    "itemId"    "itemTempId"    "itemName"
-       -           -               -    
tableb    

"id"    "itemId"    "itemTempId"    "itemImageName"
"1"     \N          "T001"          "front.jpg"
"2"     \N          "T001"          "side-left.jpg"
"3"     \N          "T001"          "side-right.jpg"
"4"     \N          "T001"          "back.jpg"

插入表格后

tablea

"id"    "itemId"    "itemTempId"    "itemName"
"1"     "US01"      "T001"          "Samsung Galaxy Note 5"    

tableb //updated with the itemId from tablea where itemTempId are the same  

"id"    "itemId"    "itemTempId"    "itemImageName"
"1"     "US01"      "T001"          "front.jpg"
"2"     "US01"      "T001"          "side-left.jpg"
"3"     "US01"      "T001"          "side-right.jpg"
"4"     "US01"      "T001"          "back.jpg"

1 个答案:

答案 0 :(得分:1)

TRIGGER中插入一行后,您可以使用tableb更新tablea

CREATE TRIGGER new_trigger 
AFTER INSERT ON tablea
FOR EACH ROW 
  UPDATE tableb SET itemId = NEW.itemID WHERE itemTempID = NEW.itemTempID;

我认为如果没有TRIGGER你就无法做到这一点,就像这样,它真的很简单。