在Mysql中可变地设置列 [英] Setting columns variably in Mysql

查看:25
本文介绍了在Mysql中可变地设置列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作的语法是什么:

What would be the syntax for doing the following:

INSERT INTO table
SET 
IF *expression*
column1 = 'value1'
ELSE
column2 = 'value2'

推荐答案

您将使用 insert ...使用 case 语句选择:

You would use insert . . . select with a case statement:

INSERT INTO table(column1, column2)
    select (case when *expression* then 'value1' end) as column1,
           (case when not *expression* then 'value2' end) as column2;

但是,我怀疑您可能真的想要一个 update 而不是 insert:

However, I suspect that you might really want an update and not an insert:

update table
    set column1 = (case when *expression* then 'value1' else column1 end),
        column2 = (case when not *expression* then 'value2' else column2 end);

这篇关于在Mysql中可变地设置列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆