2014-02-20 39 views
3

一個非常基本的問題,我有一個更新,當我進行更新時,我想要做更新,然後影響2000 +行,但是當我在子查詢中執行select查詢時,我得到1726行。我知道我的更新聲明中有錯,請問有人可以幫忙嗎?爲什麼我的更新sql查詢中會影響不同的值?

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?

回答

1

因爲您正在更新行,所以不應該更新。

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 
        ); 

我個人而言,像第一個更好的。

+1

十分感謝亞歷山大,我想的是,我是在是造成這一問題將pluc_dt,它應該是一個ship_num在爲ship_num是獨一無二的。 – niceguy

2

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

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)。

+0

感謝戈登·利諾夫,這並沒有工作,因爲我覺得把,而不是在那裏pluc_dt中我應該放在哪裏ship_num在 – niceguy

0

我查你查詢,也許這可以幫助:在這個子查詢ship_plu表

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 

加盟臺船。如果沒有關係結果在舶表(條件s.rcv_dt爲null必須被滿足),不會返回從ship_plu表值。

這意味着更新命令更新也記載,它具有相同的價值pluc_dt但其舶表的關係,不滿足條件s.rcv_dt爲空。

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

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 
     ) 

希望它能幫助!

馬立克

相關問題