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

Update with a subquery in MySQL(在 MySQL 中使用子查询进行更新)
本文介绍了在 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 中使用子查询进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)