MYSQL使用来自不同表的外键将数据插入表中

时间:2016-07-04 14:44:24

标签: mysql database stored-procedures

我有一个临时表“teststepdump”由“LOAD DATA LOCAL INFILE”创建。临时表包含表TestResult:

中由外键连接的不同表的数据
  1. teststepdump(dummyno,stationno,name,result)
  2. duttest(ID,DUTID,processTime)
  3. dut(ID,DummyNr)
  4. 站(ID,stationno)
  5. teststepname(ID,name)
  6. teststepresult(DUTTestID,TeststepID,结果)
  7. 我正在尝试使用存储过程,但我收到错误1452:

      

    SQL Fehler(1452):无法添加或更新子行:外键   约束失败(databaseteststepresult,CONSTRAINT   teststepresult_ibfk_1外键(DUTTestID)参考duttest   (ID)ON UPETE CASCADE ON UPDATE CASCADE)

    BEGIN
    DECLARE dt_id INT;
    SELECT teststepresult.DUTTestID INTO dt_id FROM teststepresult
    INNER JOIN duttest ON teststepresult.DUTTestID = duttest.ID
    INNER JOIN dut ON duttest.DUTID = dut.ID
    INNER JOIN station ON duttest.StationID = station.Nummer
    INNER JOIN teststepdump ON teststepresult.ID = teststepdump.ID
    WHERE
    dut.DummyNr = teststepdump.dummyno AND
    station.Nummer = teststepdump.stationno;
    
    INSERT INTO teststepresult (DUTTestID, TeststepID, Result) 
    SELECT dt_id, teststepname.ID, teststepdump.Result 
    FROM teststepdump
    INNER JOIN teststepname ON teststepdump.name = teststepname.name
    WHERE 
    teststepname.name = teststepdump.name;
    terminate teststepdump;
    END
    

    对于单个INSERT,这个存储过程对我有效,但我想避免使用“for”循环;:

    BEGIN
    
    DECLARE t_id INT;
    DECLARE tn_id INT;
    
    SELECT teststepname.ID INTO tn_id FROM teststepname 
    WHERE  teststepname.Name = name;
    
    SELECT duttest.ID INTO t_id FROM duttest
    INNER JOIN dut ON duttest.DUTID = dut.ID 
    INNER JOIN station ON duttest.stationID = station.ID
    WHERE
    dut.DummyNr = dummyno AND 
    station.Nummer = stationno;
    
    IF NOT t_id IS NULL AND NOT tn_id IS NULL THEN
    INSERT INTO teststepresult (DUTTestID, TeststepID, Result) 
    VALUES (t_id, tn_id, Result);
    END IF;
    END
    

1 个答案:

答案 0 :(得分:1)

我解决了问题!

BEGIN
INSERT INTO teststepresult (DUTTestID, StepName, Result) 
SELECT duttest.DUTID, teststepdump.name, teststepdump.Result 
FROM duttest
INNER JOIN dut ON duttest.DUTID = dut.ID
INNER JOIN station ON duttest.StationID = station.ID
INNER JOIN teststepdump ON dut.DummyNr = teststepdump.dummyno
WHERE 
dut.DummyNr = teststepdump.dummyno AND
station.Nummer = teststepdump.stationno;
#truncate teststepdump; 
END