MySQL 如果决定多个字段?

MySQL IF deciding multiple fields?

根据复杂的条件,我需要插入一组字段。

我想做的是(伪代码)

IF (condition) DO
  INSERT INTO table set columnA= "foo", columnB = "bar"
ELSE
  INSERT INTO table set columnA= "no foo", columnB = "no bar"
ENDIF

不幸的是,我不能使用存储过程,我必须将其放入常规语句中。

我可以为每一列重复条件

INSERT INTO table (columnA, columnB) SELECT IF(condition, "foo", "no foo"), IF(condition, "bar", "no bar")

但条件本身很复杂且嵌套,所以我尽量不重复。

是否有一种语法可以让单个 IF 或 CASE 决定多个列?

不完全是。但看起来您的情况与行无关。你可以这样做:

INSERT INTO table(columnA, columnB)
    select (case when flag = 1 then 'foo' else 'no foo' end),
           (case when flag = 1 then 'bar' else 'no bar' end)
    from (select <condition> as flag) x;

你确实得到了一个带有 SELECT ... FROM:

WHERE 子句

您可以将其分成两个单独的查询,但是,这是两个查询:

INSERT INTO table (columnA, columnB)
SELECT 'foo', 'bar'
WHERE :foo;

INSERT INTO table (columnA, columnB)
SELECT 'no foo', 'no bar'
WHERE NOT :foo;

变量是你的朋友 ;-)

 INSERT INTO table (columnA, columnB)
 SELECT IF(@condition:=<your condition goes here>, "foo", "no foo"),
        IF(@condition, "bar", "no bar");

不是说可以使用EXISTS(SELECT something)作为有效条件

怎么样

  INSERT INTO table 
    SELECT "foo", "bar" FROM something WHERE (condition)
    UNION
    SELECT "no foo", "no bar" FROM something WHERE NOT(condition)