在一行 SQL 中更新两个不同的行

编程入门 行业动态 更新时间:2024-10-08 12:44:42
本文介绍了在一行 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 中更新两个不同的行

本文发布于:2023-07-09 10:35:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085646.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!