Update with a subquery in 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 中使用子查询进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 MySQL 中使用子查询进行更新
基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01