【问题标题】:SQL Update, subquery returns more than one rowSQL 更新,子查询返回多行
【发布时间】:2012-08-28 16:27:28
【问题描述】:
Timezones
---------
-AreaCode varchar
-Timezone varchar

Contacts
--------
-Phone    varchar
-Timezone varchar

除了联系人表中的Timezone 之外,所有内容都已填充,因此我想查找每个电话号码的时区并更新联系人。这是我尝试做的,但MySQL 给出了

错误 1242 子查询返回多行

对于每个时区 (0,-1,-2,-3,-4,-5),我执行此更新:

update contacts 
set contacts.timezone = '-1' 
where left(contacts.phone,3) = (Select timezones.areacode 
                                from timezones 
                                where timezones.timezone = '-1');

【问题讨论】:

  • 那么,您是否验证过确实每个ID只有一个时区?
  • 我刚查了一下,时区表中没有重复的区号
  • 我问的是重复的timezone 值,而不是重复的区号。

标签: mysql subquery sql-update


【解决方案1】:

您的子查询返回不止一行。只需将“=”替换为“IN”即可处理此问题:

update contacts 
set contacts.timezone = '-1' 
where left(contacts.phone,3) in (Select timezones.areacode 
                                from timezones 
                                where timezones.timezone = '-1');

【讨论】:

    【解决方案2】:

    在更新或子查询上尝试内连接:

    update contacts 
    set contacts.timezone = '-1' 
    where left(contacts.phone,3) in (Select timezones.areacode 
                                    from timezones 
                                    where timezones.timezone = '-1');
    

    【讨论】:

      【解决方案3】:

      问题是时区中可能有超过 1 行具有 timezone column = '-1'

      您可以在此处使用Join

      update contacts join timezones on left(contacts.phone,3) = timezones.areacode and timezones.timezone = '-1'
      set contacts.timezone = '-1';
      

      它将区号与手机匹配,在这种情况下将更新为'-1'

      【讨论】:

        【解决方案4】:

        更改 where 部分,例如: ....

        where left(...) in (select ...... ) 
        

        【讨论】:

          猜你喜欢
          • 2019-10-02
          • 2015-09-20
          • 1970-01-01
          • 1970-01-01
          • 2016-08-16
          • 2017-08-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多