2016-05-26 27 views
1

我有兩個表:如何通過連接其他表來插入到一個表中?

table1 
id | mcc | mnc | active | client_id 
1 202 05  1  4 
2 202 06  0  4 
.......a lot 

table2 
id | mcc | mnc | rejectReason 
1 202 05   null 
2 202 06   null 

需要插入到表2,但需要檢查每個表1的項目爲表2是這樣的插入:

SELECT table1 t1 

(CASE WHEN t2.id != 0 
THEN 
    INSERT INTO table2 t22 
    SET (
     t22.rejectReason = CONCAT('LOSS OF COVERAGE'), 
     t22.mcc = t1.mcc, 
     t22.mnc = t1.mnc, 
) 
WHERE t22.mcc  = t1.mcc 
AND t22.mnc  = t1.mnc 
ELSE 
    '' 
END) 

LEFT JOIN table2 t2 
ON t2.mcc  = t1.mcc 
AND t2.mnc  = t1.mnc 

如果table1中還沒有這個項目( mcc/mnc)like table2,然後爲table2插入當前項目。請幫助

RESULT: 

table1 
 
    id | mcc | mnc | active | client_id 
 
    1 202 05  1  4 
 
    2 202 06  0  4 
 
    3 214 0  1  5 
 
    ..... 
 
     212 16  // not exist 
 
     214 07  // not exist 
 
    .......a lot 
 
    
 
    table2 
 
    id | mcc | mnc | rejectReason 
 
    1 202 05   null 
 
    2 202 06   null 
 
    3 212 16   LOSS OF COVERAGE // then insert 
 
    4 214 07   LOSS OF COVERAGE // then insert

回答

1

嗯,我不太明白你想要什麼,但在這裏是應該的結構,調整到你的意思:

UPDATE table2 t2 
LEFT JOIN table1 t1 
ON(t1.mcc = t2.mcc and t1.mnc = t2.mnc) 
SET t2.rejectReason = 'LOSS OF COVERAGE' 
WHERE t1.id is null 

如果表1中沒有相同的mcc,mnc記錄,則會將t2.rejectReason更新爲「損失覆蓋率」。順便說一下,CONCAT()用於聯合多個字符串,你也有一個,所以你不需要它。

編輯:如果你想然後插入:

INSERT INTO table2 
SELECT t.id,t.mcc,t.mnc,'LOSS OF COVERAGE' 
FROM Table1 t 
WHERE NOT EXISTS(SELECT 1 from table2 s 
       WHERE t.mcc = s.mcc and t.mnc = s.mnc) 

EDIT2:我不知道這個錯誤,所以也許可以更容易解決,但你可以這樣做:

CREATE TABLE Temp_Tbl AS 
(SELECT t.id,t.mcc,t.mnc,'LOSS OF COVERAGE' 
FROM Table1 t 
WHERE NOT EXISTS(SELECT 1 from table2 s 
       WHERE t.mcc = s.mcc and t.mnc = s.mnc)); 

INSERT INTO Table2 
SELECT * FROM Temp_Tbl; 

DROP TABLE Temp_Tbl; 
+0

對不起,我困惑,我需要插入,我編輯=/ – axon

+0

你究竟想要發生什麼?請提供預期的輸出。 – sagi

+0

我添加了結果,我需要我認爲 – axon

相關問題