【问题标题】:MySQL: Update rows in table, from rows with matching key in another tableMySQL:从另一个表中具有匹配键的行更新表中的行
【发布时间】:2015-10-27 07:57:04
【问题描述】:

我有一个包含现有数据的表users,我将更新的数据上传到一个临时表users_temp

我正在尝试创建两个查询,一个用于更新 users 中的 namedepartment_id 行,并在匹配 id 时使用来自 users_temp 的数据。

另一个是删除users 中与users_temp 中的id 不匹配的行。

请帮忙。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您可以通过在更新中添加联接来做到这一点。

    UPDATE users u 
    INNER JOIN users_temp ut on u.id = ut.id //or whatever the matching fields are
    SET u.name = ut.name, u.department_id = ut.department_id;
    

    我相信有人会为第二个查询提供一个更有效的示例,但这可以解决问题:

    Delete all rows which has no id existing in another table

    【讨论】:

      【解决方案2】:
      update users
      inner join users_temp using (id)
      set users.name = users_temp.name,
      users.department_id = users_temp.department_id
      
      delete from users
      where not exists (select * from users_temp where users_temp.id = users.id)
      

      【讨论】:

      • 如果您只是要过滤掉WHERE 子句中的不匹配行,为什么要使用LEFT JOIN?使用INNER JOIN,这样它们就不会被包含在第一位。
      • 谢谢,它成功了。如果用户中不存在该行,您能否添加一个查询,将 users_temp 中的行复制到用户中?
      猜你喜欢
      • 2021-07-23
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 2019-10-27
      • 2021-01-11
      • 1970-01-01
      相关资源
      最近更新 更多