我有PHP数组(数组具有多个值),我想在表中添加该数据,但是在插入表中之前先检查另一个表中是否存在值,如果在另一个表中获取值则跳过该值。
示例:
INSERT INTO table1('column1','column2','column3') VALUES
('val11','val11','val11'),
('val12','val12','val12')
WHERE NOT EXIST
(SELECT * FROM table2 WHERE table2.column1 = VALUES(column1) AND
table2.column2 = VALUES(column2) AND table2.column3 = VALUES(column3)
我是走正确的道路还是有更好的方法呢?
谢谢
Miten
答案 0 :(得分:0)
您需要使用INSERT ... SELECT
语法来实现此结果。因为您有多行,所以必须将数据行UNION
放入一个派生表中,然后检查该表中的值在table2
中是否不存在:
INSERT INTO table1 (column1, column2, column3)
SELECT *
FROM (SELECT 'val11' AS column1, 'val12' AS column2, 'val13' AS column3
UNION
SELECT 'val21', 'val22', 'val23') v
WHERE NOT EXISTS (SELECT *
FROM table2 t2
WHERE t2.column1 = v.column1
AND t2.column2 = v.column2
AND t2.column3 = v.column3)