Mysql使用If语句移动到下一列

时间:2013-02-07 18:57:42

标签: php mysql phpmyadmin

我想更新一个MySQL表。使用UPDATE功能。

我的专栏是:

time_started, time_in_1, time_in_2, time_in_3.

我想要的是time_started不为null然后移动到下一列但是如果time_in_1也不为null则移动到下一列,依此类推。任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

UPDATE table 
  SET time_started = IFNULL(time_started, newValue, time_started), 
       time_1 = IFNULL(time_1, newValue, time_1),
       time_2 = IFNULL(time_2, newValue, time_2);

如果NULL,则会将每列设置为newValue,否则保留其原始值。

答案 1 :(得分:0)

首先让我说这看起来像一个非常奇怪的(并且不是非常可扩展的)表结构。所需的SQL并不完美,我想说将它扩展到几列后不会让任何人高兴:)

那说,这应该做你想要的;

SET @value := '2001-01-01';

UPDATE myTable SET
  time_in_3 =    IF(time_started IS NOT NULL AND
                    time_in_1    IS NOT NULL AND
                    time_in_2    IS NOT NULL AND
                    time_in_3    IS NULL, @value, time_in_3),
  time_in_2    = IF(time_started IS NOT NULL AND
                    time_in_1    IS NOT NULL AND
                    time_in_2    IS NULL, @value, time_in_2),
  time_in_1    = IF(time_started IS NOT NULL AND
                    time_in_1    IS NULL, @value, time_in_1),
  time_started = IF(time_started IS NULL, @value, time_started)
WHERE id=1;

An SQLfiddle showing it in action