2016-07-04 71 views
0

我有一個由「LOAD DATA LOCAL INFILE」創建的臨時表「teststepdump」。臨時表包含一起在表TestResult中由外鍵連接的不同的表的數據:MYSQL使用來自不同表的外鍵將數據插入表

  1. teststepdump(dummyno,stationno,名稱,結果)
  2. duttest(ID,DUTID,processTime)
  3. DUT (ID,DummyNr)
  4. 站(ID,stationno)
  5. teststepname(ID,姓名)
  6. teststepresult(DUTTestID,TeststepID,結果)

我正嘗試使用存儲過程這種方式,但我得到錯誤1452:

SQL Fehler(1452):不能添加或更新子行,外鍵約束 失敗(databaseteststepresult,約束 teststepresult_ibfk_1外鍵(DUTTestID)參考文獻duttestID)ON DELETE 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」Loop;:

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 
+0

你能向我們展示table'testtepdump'的結構嗎? (我的意思是創建sql代碼) –

+0

CREATE TABLE'teststepdump'( 'ID' INT(11)NOT NULL AUTO_INCREMENT, 'dummyno' BIGINT(20)NOT NULL DEFAULT'0', 'stationno' INT(11) NOT NULL DEFAULT'0', 'name' VARCHAR(50)NOT NULL DEFAULT'0'COLLATE'utf8_bin','Result' TINYINT(4)NULL DEFAULT NULL, PRIMARY KEY('ID') – Fantomas

+0

它看起來沒有'沒有外鍵...你能顯示'teststepresult'的結構嗎? –

回答

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