MySQL - 在一个查询中更新具有不同值的多行

MySQL - UPDATE multiple rows with different values in one query(MySQL - 在一个查询中更新具有不同值的多行)
本文介绍了MySQL - 在一个查询中更新具有不同值的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图了解如何使用不同的值更新多行,但我不明白.解决方案无处不在,但在我看来很难理解.

I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.

例如,三个更新为 1 个查询:

For instance, three updates into 1 query:

UPDATE table_users
SET cod_user = '622057'
    , date = '12082014'
WHERE user_rol = 'student'
    AND cod_office = '17389551'; 

UPDATE table_users
SET cod_user = '2913659'
    , date = '12082014'
WHERE user_rol = 'assistant'
    AND cod_office = '17389551'; 

UPDATE table_users
SET cod_user = '6160230'
    , date = '12082014'
WHERE user_rol = 'admin'
    AND cod_office = '17389551'; 

我 阅读 一个例子,但我真的不明白如何进行查询.即:

I read an example, but I really don't understand how to make the query. i.e:

UPDATE table_to_update
SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230')
    ,date = IF(cod_office = '17389551','12082014')
WHERE ?? IN (??) ;

如果 WHERE 和 IF 条件中有多个条件,我不完全清楚如何进行查询..有什么想法吗?

I'm not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?

推荐答案

你可以这样做:

UPDATE table_users
    SET cod_user = (case when user_role = 'student' then '622057'
                         when user_role = 'assistant' then '2913659'
                         when user_role = 'admin' then '6160230'
                    end),
        date = '12082014'
    WHERE user_role in ('student', 'assistant', 'admin') AND
          cod_office = '17389551';

我不明白你的日期格式.日期应使用本机日期和时间类型存储在数据库中.

I don't understand your date format. Dates should be stored in the database using native date and time types.

这篇关于MySQL - 在一个查询中更新具有不同值的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Simulating MySQL#39;s ORDER BY FIELD() in Postgresql(在 Postgresql 中模拟 MySQL 的 ORDER BY FIELD())
Using MySQL query to traverse rows to make a recursive tree(使用MySQL查询遍历行制作递归树)
MySQL LOAD DATA INFILE with ON DUPLICATE KEY UPDATE(MySQL LOAD DATA INFILE 和 ON DUPLICATE KEY UPDATE)
Search for quot;whole word matchquot; in MySQL(搜索“全字匹配在 MySQL 中)
add column to mysql table if it does not exist(如果不存在,则将列添加到 mysql 表)
MIN/MAX vs ORDER BY and LIMIT(MIN/MAX 与 ORDER BY 和 LIMIT)