在 MySQL 中使用子查询进行更新

2022-01-23 00:00:00 sql-update subquery 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.

相关文章