我有两张桌子:
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
需要插入到table2中,但需要检查table1的每个项目,以便插入table2:
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没有像table2这样的项目(mcc / mnc),那么为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

答案 0 :(得分: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
这会将t2.rejectReason
更新为“覆盖范围内”'当表1中没有相同mcc,mnc
的记录时。顺便说一下,CONCAT()
用来联合多于1个字符串,你也有一个字符串,所以你不需要它。 / p>
编辑:如果您想要插入,那么:
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;