我正在尝试比较来自不同表的数据,插入新数据以及更新不匹配的数据。
示例:
I have table1 ------------------------------------ | ITEMNO | DESCRIPTION | FORSALE | ------------------------------------ | 123456 | Description1 | YES | ------------------------------------ | 234567 | Description2 | YES | ------------------------------------ | 345678 | Description3 | YES | ------------------------------------
我也有table2,它只是一个临时表
---------- | ITEMNO | ---------- | 123456 | ---------- | 234567 | ----------
ITEMNO是table1中的主键和Table2中的外键
因此,当程序中的模块发送数据时,它将首先检查table2,然后将数据与表1进行比较
如果发送的数据是这样的
table2 table1 ---------- ---------- | ITEMNO | | ITEMNO | ---------- ---------- | 123456 | = | 123456 | (MATCH WITH TABLE1 AND TABLE2 THEN UPDATE) ---------- ---------- | 234567 | = | 234567 | (MATCH WITH TABLE1 AND TABLE2 THEN UPDATE) ---------- ---------- | 567890 | = | 567890 | (NEW DATA THEN INSERT INTO TABLE 1) ---------- ---------- | 345678 | (DOESN'T EXIST IN TABLE2 BUT EXISTS IN TABLE 1 SO UPDATE FORSALE FIELD TO "NO") ----------
任何帮助将不胜感激,提前谢谢。
答案 0 :(得分:0)
你可以通过2 sql以下来实现它 -
UPDATE table1 AS t1
LEFT JOIN table2 AS t2 ON t1.itemno=t2.itemno
SET t1.FORSALE='No'
WHERE t2.itemno IS NULL;
INSERT IGNORE INTO table2 (itemno) SELECT t1.itemno
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t1.itemno=t2.itemno
WHERE t2.itemno IS NULL;
但更好的选择是使用存储过程,它将首先从下面的查询中获取未匹配的itemno并将其保存在游标中然后根据主键更新和插入,因为它可以避免锁定 -
SELECT t1.itemno
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t1.itemno=t2.itemno
WHERE t2.itemno IS NULL;
答案 1 :(得分:0)
您需要2个查询。你可以试试这个:
//NEW DATA THEN INSERT INTO TABLE 1
insert into table1(item_no,description)
select item_no,description
from table2
where item_no not in(
select item_no from table1
);
和
//DOESN'T EXIST IN TABLE2 BUT EXISTS IN TABLE 1 SO UPDATE FORSALE FIELD TO "NO"
update table1
set forsale = 'NO'
where item_no not in(
select item_no from table2
)
如果TABLE1 AND TABLE2
匹配则无法执行操作。