【问题标题】:Advanced MySql Query: Update table with info from another table高级 MySql 查询:使用另一个表中的信息更新表
【发布时间】:2009-07-29 18:14:48
【问题描述】:

我想用另一个表中的数据更新 mySql 中的一个表。

我有两个表“人”和“业务”。人员表通过名为“business_id”的列链接到业务表。

必要的表结构,主键加星号(表:列): 人员:*business_id、*sort_order、电子邮件 业务:*business_id、电子邮件

我想用人员表中的电子邮件更新业务表电子邮件列,如下所示(我知道我在这里遗漏了一些东西):

UPDATE business b SET email = (SELECT email  from People p where p.business_id = b.business_id AND sort_order = '1') WHERE b.email = ''; 

这有意义吗?有可能吗?

【问题讨论】:

    标签: mysql sql-update


    【解决方案1】:
    UPDATE business b, people p
       SET b.email = p.email
     WHERE b.business_id = p.business_id
       AND p.sort_order = '1'
       AND b.email = ''
    

    【讨论】:

    • 非常好,但我这边最多需要 3 秒
    【解决方案2】:

    注意,如果 sort_order 是一个 INT,那么不要使用 '1' - 使用 1:

    UPDATE business b
    JOIN People p
    ON p.business_id = b.business_id
    AND p.sort_order = '1'
    SET b.email = p.email
    WHERE b.email = '';
    

    【讨论】:

      【解决方案3】:

      试试这个,它对我来说很好。

      Update table a, table b
      Set a.importantField = b.importantField,
      a.importantField2 = b.importantField2
      where a.matchedfield = b.matchedfield;
      

      【讨论】:

      • 一般来说,如果答案包含对代码的用途的解释,以及为什么在不介绍其他人的情况下解决问题的原因,答案会更有帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      相关资源
      最近更新 更多