【问题标题】:how to update table based on another table in mysql?如何根据mysql中的另一个表更新表?
【发布时间】:2012-01-23 19:11:17
【问题描述】:

我有 2 张桌子作为休闲用具:

users
zip      state      city
89012    
45869     0
....


zips
zip      state      city
89012    NV         lv
45869    MI         ca
....

我想根据users 表中的zip 以有效的方式使用zips 中的state and city 更新users: state and city

users 表中的city 为空,但state 也可以为0 或空

有什么想法吗?

谢谢

【问题讨论】:

    标签: mysql select


    【解决方案1】:

    您是否尝试批量更新所有现有行?

    如果是这样,这是进行更新的一种方法:

    update users u
      inner join zips z on z.zip = u.zip
    set u.state = z.state,
      u.city = z.city;
    

    【讨论】:

    • 应该有(city <> '' and state <> '') or (city <> '' and state <> '0')之类的条件
    • 当然,您可以根据您的要求优化查询,以不将好的数据替换为坏的数据等。我只是按照您在原始问题中给出的要求工作。
    猜你喜欢
    • 2012-09-05
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多