使用 MySQL 中的子查询更新 [英] Update with a subquery in MySQL

查看:78
本文介绍了使用 MySQL 中的子查询更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个更新查询需要在 MySQL 中运行,但遇到了一些问题.我花了最后一个小时研究 SO 以寻求解决方案,但找不到真正有效的解决方案.我需要执行以下操作:

I have an update query that I need to run in MySQL and am having some trouble with it. I have spent the last hour researching SO for a solution, but couldn't find one that actually worked. I need to do the following:

UPDATE TABLE1 SET ID = (SELECT TABLE2.ID FROM TABLE2, TABLE1 
WHERE TABLE1.NAME=TABLE2.NAME) WHERE TABLE1.ID IS NULL

我一直收到错误代码:1242.子查询返回多于1行错误.如何修改我的查询以使其成功运行?

I have been getting the Error Code: 1242. Subquery returns more than 1 row error. How can I modify my query to make it run successfully?

基本上,我需要根据条件,从另一个表中填充一列的所有值的空白.请指导我解决这个问题.谢谢!

Basically, I need to fill in the blanks of all values of one column based on a condition, from another table. Please guide me on this issue. Thank you!

推荐答案

UPDATE TABLE1, TABLE2 
  SET TABLE1.ID = TABLE2.ID
  WHERE TABLE1.ID IS NULL
  AND TABLE1.NAME = TABLE2.NAME

可能应该做你想做的事情,假设 NAME 对于所有名称在 TABLE1 和 TABLE2 中都是唯一的.

should probably do what you want, assuming that NAME is unique accross TABLE1 and TABLE2 for all names.

这篇关于使用 MySQL 中的子查询更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆