【问题标题】:Why are different values being affected in my update sql query?为什么我的更新 sql 查询中会影响不同的值?
【发布时间】:2014-03-21 17:57:10
【问题描述】:

一个非常基本的问题,我有一个更新我想做的更新,然后它会影响 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?

【问题讨论】:

    标签: sql select subquery


    【解决方案1】:

    因为您正在更新行,所以不应更新。

    ship_plu.pluc_dt 可能满足条件,而ship_plu.ship_num

    这是错误的更新方式。

    你应该试试:

    更新 ship_plus sp 加入船舶 ON sp.ship_num=s.ship_num 设置 pluc_dt='1-Jan-1999' 其中 pluc_dt 在“2014 年 2 月 16 日”和“2014 年 2 月 20 日”之间 并且 s.rcv_dt 为空;

    另一种选择(假设ship_num 是唯一的并且某处有外键)是:

    更新ship_plu 设置 pluc_dt='1-Jan-1999' 其中ship_num在( 选择 sp.ship_num 来自 ship_plus sp,ship s 其中 sp.pluc_dt 在“2014 年 2 月 16 日”和“2014 年 2 月 20 日”之间 和 sp.ship_num=s.ship_num 并且 s.rcv_dt 为空 );

    我个人更喜欢第一个。

    【讨论】:

    • 非常感谢 Alexander,我认为我放入 pluc_dt 的事实导致了问题,它应该是 ship_num 的位置,因为 ship_num 是唯一的。
    【解决方案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)。

    【讨论】:

    • 感谢 Gordon Linoff,这没有用,因为我认为与其把 pluc_dt 放在哪里,不如把 ship_num 放在哪里
    【解决方案3】:

    我检查了您的查询,也许这会有所帮助:

        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。如果 ship 表中没有关系结果(必须满足条件 s.rcv_dt 为 null),则不返回 ship_plu 表中的值。

    表示update命令也更新记录,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
            )
    

    希望对你有帮助!

    马雷克

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2019-05-08
      • 2011-06-17
      • 2021-03-10
      • 1970-01-01
      相关资源
      最近更新 更多