Update two different rows in one line of SQL(在一行 SQL 中更新两个不同的行)
问题描述
假设我有一个名为 example 的表:
Say I have a table called example as:
[abc] |[定义]
[abc] | [def]
--1---|-qwerty-
--1---|-qwerty-
--2---|-asdf---
--2---|-asdf---
我想要做的是更新一个 SQL 查询中的两列(仅使用一个 UPDATE).
What I am wanting to do is update both columns in one SQL query (using only one UPDATE).
UPDATE example SET def = 'foo' where abc = '1'
UPDATE example SET def = 'bar' where abc = '2'
以上是我想要实现的,但是在一行 sql 中(使用 MySQL).我知道您可以像 UPDATE example SET def 'foo', SET def = 'bar' 那样执行此操作,但我不确定您如何使用两个不同的 where 语句来执行此操作.
The above is what I am wanting to achieve but in one line of sql (using MySQL). I know you can do this like UPDATE example SET def 'foo', SET def = 'bar' but I'm not sure how you can do this with two different where statements.
推荐答案
你可以使用IF执行一个UPDATE(mysql支持)em>) 或使用 CASE 使其对 RDBMS 更友好.
You can execute one UPDATE with the use of IF (which mysql supports) or by using CASE to make it more RDBMS friendly.
UPDATE example
SET def = IF(abc = 1, 'foo', 'bar')
WHERE abc IN (1, 2) -- reason to make it more faster, doesn't go on all records
或
UPDATE example
SET def = CASE WHEN abc = 1 THEN 'foo' ELSE 'bar' END
WHERE abc IN (1, 2) -- reason to make it more faster, doesn't go on all records
这篇关于在一行 SQL 中更新两个不同的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在一行 SQL 中更新两个不同的行
基础教程推荐
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
