SQL - 行的比较和更新表?

时间:2016-12-22 15:00:31

标签: mysql sql

我有两张桌子,例如:

firstfile

secondfile是我的源表,firstfile是目标表。现在我需要一个查询,查找secondfile中表Table secondfile ================ Emplid | Color | Status ------------------------------- 123 | red | 456 | Green | 000 | red | 789 | black | 999 | white | 777 | orange | Removed 中不存在的所有行。所以我需要一个查询,它找到了以下内容:

CASE WHEN

UPDATE second file set status = (CASE WHEN first file.Emplid not In (select Emplid from secondfile) THEN 'Remove' END); 格式进行此类查询的有效方法是什么?

我尝试了这个,但它不起作用:

 if(!([string]::Compare($filestmp.Substring(0,1), "M", $True)))
 {
     echo cos
     $filestmp = $filestmp.Replace('^(.*?)M(.*)', 'Zmodyfikowany  ')
 }

2 个答案:

答案 0 :(得分:1)

你不能UPDATE一行不存在,你可以INSERT换一行。

您可以使用NOT IN功能执行此操作:

INSERT INTO secondfile
SELECT  f.Emplid,f.Color, 'Removed' 
FROM    firstfile f
WHERE   f.Emplid NOT IN (SELECT 1 FROM secondfile s WHERE f.Emplid=s.Emplid)

或使用NOT EXISTS功能:

INSERT INTO secondfile
SELECT f.Emplid,f.Color, 'Removed'
FROM firstfile f 
WHERE NOT EXISTS(SELECT s.Emplid FROM secondfile s)

您也可以使用JOIN

执行此操作
INSERT INTO secondfile
SELECT f.Emplid,f.Color, 'Removed'
FROM firstfile f 
LEFT OUTER JOIN secondfile s ON f.Emplid = s.Emplid 
WHERE s.Emplid IS NULL;

答案 1 :(得分:0)

我认为您实际上在寻找INSERT而不是UPDATE

INSERT INTO secondfile (Emplid, Color, Status)
SELECT EmplId, Color, 'Removed' 
FROM firstfile AS t1
WHERE NOT EXISTS (SELECT 1
                  FROM secondfile AS t2
                  WHERE t1.Emplid = t2.Emplid AND t1.Color = t2.Color)