更新满足以下条件的行

Posted

技术标签:

【中文标题】更新满足以下条件的行【英文标题】:Update Rows Where the following conditions are true 【发布时间】:2020-05-12 22:38:10 【问题描述】:

我正在尝试用另一个表中的值覆盖某个字段值,其中某个条件为真。我在下面模拟了我的代码

伪代码:

Where an employee has the team Ops in old_data, get their new team from new_data and overwrite the team in old_data

我的代码:

UPDATE old_data -- This has columns Employee, Latest_Team
SET
    Latest_Team = 
           (select new_data.team
            from new_data
            left join old data
            ON old_data.employee = new_data.employee
           )
WHERE old_data.employee = 'Ops'

但这会返回错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

我不确定我到底哪里出错了

【问题讨论】:

(1) 请用您正在使用的数据库标记您的问题 (2) 示例数据和预期结果肯定会帮助其他人了解您到底在寻找什么。 您的选择语句返回多于 1 行。所以最新的 Team 不能匹配 1 且只有 1 行 【参考方案1】:

如果您正在寻找团队“操作”,那么您的查询有几个问题:

您过滤的是员工,而不是团队。 您在内部 from 子句中有错字。 您需要一个相关的子查询。

所以,我想你想要:

UPDATE old_data -- This has columns Employee, Latest_Team
    SET Latest_Team = (select nd.team
                       from new_data nd
                       where old_data.employee = nd.employee
           )
WHERE od.latest_team = 'Ops';
------^  I think this is the filter you describe

【讨论】:

谢谢,这行得通。你会如何通过加入来做到这一点? @andre1990 。 . .许多数据库不支持update 中的join 语法。那些确实有不同的语法。无法笼统地回答您评论中的问题。【参考方案2】:

确保此查询不返回任何内容并且您的代码可以正常工作

select new_data.team, count(*)
            from new_data
            left join old data WHERE old_data.employee = 'Ops'
group by new_data.team
having count(*) > 1

如果您的每位员工拥有多个团队且 Old_data.employee = 'Ops',则 sql 将不知道为该员工选择哪个进行更新

【讨论】:

【参考方案3】:

您的联接中有错字 - “旧数据”应该是“旧数据”。

也许这可以帮助你:update columns values with column of another table based on condition

在你的例子中是:

UPDATE old_data SET
    Latest_Team = (SELECT new_data.team FROM new_data WHERE old_data.employee = new_data.employee LIMIT 1)
    WHERE old_data.employee = 'Ops';

【讨论】:

以上是关于更新满足以下条件的行的主要内容,如果未能解决你的问题,请参考以下文章

MYSQL 存储过程 - 如果满足某些条件,则更新多个列

Oracle:Sql根据同一表另一行的值更新同一表的行

在oracle中,我想更新数据,但是满足条件的有多条数据,用update怎么逐条更新呢,在线等

更新PostgreSQL数据

位置管理器的位置更新请求是不是仅在满足最小距离条件后才发生?

如果存在并满足多个条件,如何更新行,否则如何在 SQL Server 中插入