簡體   English   中英

為什么在我的更新sql查詢中會影響不同的值?

[英]Why are different values being affected in my update sql query?

一個非常基本的問題,我有一個更新,我想做更新,然后它影響2000多行,但當我只是在子查詢中執行選擇查詢,然后我得到1726行。 我知道我的更新聲明中有問題,有人可以幫忙嗎?

update ship_plu 
   set pluc_dt='1-Jan-1999' 
 where pluc_dt in (
                   select sp.pluc_dt 
                     from ship_plu sp,ship s 
                    where sp.pluc_dt between '16-Feb-2014' and '20-Feb-2014'
                          and sp.ship_num=s.ship_num 
                          and s.rcv_dt is null
                   )

因此,在執行的子查詢上方只返回1726行,但是當我執行整個更新查詢時,它會影響超過2000行,我想只執行1726行?

您想要一個相關的子查詢。 但是你有內部子查詢引用外部表。 嘗試這個:

update ship_plu sp
   set pluc_dt='1-Jan-1999' 
 where pluc_dt in (
                   select sp.pluc_dt 
                     from ship s 
                    where sp.pluc_dt between '16-Feb-2014' and '20-Feb-2014'
                          and sp.ship_num=s.ship_num 
                          and s.rcv_dt is null
                   );

這種形式的查詢可以在任何數據庫中使用。 根據您使用的實際數據庫,您可以使用其他語法(使用join )。

因為您要更新行,所以不應更新。

ship_plu.pluc_dt可能符合條件,而ship_plu.ship_num 則不符合條件。

這是更新的錯誤方法。

你應該嘗試:

update ship_plu sp 
       JOIN ship s
            ON sp.ship_num=s.ship_num 
   set pluc_dt='1-Jan-1999' 
 where pluc_dt between '16-Feb-2014' and '20-Feb-2014'
       and s.rcv_dt is null;

另一個選擇(假設ship_num是唯一的,而某個外鍵是):

update ship_plu 
   set pluc_dt='1-Jan-1999' 
 where ship_num in (
                   select sp.ship_num 
                     from ship_plu sp,ship s 
                    where sp.pluc_dt between '16-Feb-2014' and '20-Feb-2014'
                          and sp.ship_num=s.ship_num 
                          and s.rcv_dt is null
                   );

我個人認為,第一個更好。

我檢查了你的查詢,也許這可以幫助:

    select sp.pluc_dt 
    from ship_plu sp,ship s 
    where sp.pluc_dt between '16-Feb-2014' and '20-Feb-2014'
        and sp.ship_num=s.ship_num 
        and s.rcv_dt is null

在這個子查詢中,ship_plu表正在連接表船。 如果ship表中沒有關系結果(條件s.rcv_dt必須滿足null),則不返回ship_plu表中的值。

這意味着更新命令更新也記錄,其具有相同的值pluc_dt,但其在ship表中的關系不滿足條件s.rcv_dt為null。

我建議從查詢中返回記錄標識符。 改變你這樣查詢:

    update ship_plu 
    set pluc_dt='1-Jan-1999' 
    where ID in (
        select sp.ID 
        from ship_plu sp,ship s 
        where sp.pluc_dt between '16-Feb-2014' and '20-Feb-2014'
            and sp.ship_num=s.ship_num and s.rcv_dt is null
        )

希望能幫助到你!

馬雷克

暫無
暫無

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

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