簡體   English   中英

SQL-檢查和更新表中是否有新行?

[英]SQL - Check and Update table for new rows?

我有兩個表,例如:

Table firstfile                      Table secondfile
===============                      ================

Emplid   | Color                     Emplid       | Color   |status
----------------------               -------------|---------|------
123      | red                       123          | red     |
456      | green                     456          | Green   |
789      | black                     000          | red     | 
                                     789          | black   |
                                     999          | white   | 

表firstfile是我的源表,secondfile是目標表。 現在,我需要一個查詢,該查詢在表secondfile中查找所有不同(附加)的行。 因此,我需要一個查詢,該查詢為我找到以下內容:

Table secondfile
================

Emplid       | Color   | Status
-------------------------------
123          | red     |
456          | Green   |
000          | red     | added
789          | black   |
999          | white   | added

這樣的查詢有什么好的方法?

我嘗試了這個但是它不起作用

UPDATE secondfile 
INNER JOIN firstfile 
   ON secondfile.Emplid = firstfile.Emplid
SET status = (CASE  WHEN secondfile.Emplid != firstfile.Emplid THEN 'Added' END)

嘗試這個

    UPDATE secondfile     
    SET status = 'Added'   
    WHERE secondfile.Emplid NOT IN( select  Emplid  from firstfile)

樣品申請案例

UPDATE secondfile 
SET status =      CASE 
                        WHEN Emplid= 10 THEN 'JustAdded'
                        WHEN Emplid= 20  THEN 'NewlyAdded' 
                        WHEN Emplid= 30 THEN 'Old' 
                        ELSE 'Added'
                    END     
WHERE secondfile.Emplid not in ( select  Emplid  from firstfile)

嘗試通過以下方式使用LEFT JOINIS NULL您可以檢查第一個文件中不存在但第二個文件中不存在的記錄,它將更新相同的結果集

UPDATE secondfile 
LEFT JOIN firstfile ON secondfile.Emplid = firstfile.Emplid
SET status = 'Added'
WHERE firstfile.Emplid IS NULL

在您的代碼中,您正在使用secondfile.Emplid != firstfile.Emplid ,它將永遠不會對INNER JOIN感到滿意,此INNER JOIN始終僅返回匹配的數據,並且在您的情況下,它將返回兩個表中都存在的數據。

您可以在查詢中進行一些微小的更改,如下所示:

UPDATE secondfile 
LEFT JOIN firstfile ON secondfile.Emplid = firstfile.Emplid
SET status = CASE WHEN secondfile.Emplid != firstfile.Emplid THEN 'Added' ELSE status END

您可以使用NOT EXISTS()並執行以下操作:

UPDATE secondfile     
SET status = 'Added'   
WHERE  NOT EXITS( 
                  select  1 
                  from firstfile
                  where Emplid= secondfile.Emplid
                                                   )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM