2

在 MySQL 表中mytable我想更新列max_value

查询前的示例表如下所示:

___________________________________________________
|| id || value1 || value2 || value3 || max_value ||
___________________________________________________
|| 1  ||    1   ||   2    ||   3    ||   NULL    ||
===================================================
|| 2  ||    99  ||   2    ||   3    ||   NULL    ||
===================================================
|| 3  ||    1   ||   66   ||   66   ||   NULL    ||
===================================================
|| 4  ||    1   ||   2    ||  NULL  ||   NULL    ||
===================================================
|| 5  ||  NULL  ||  NULL  ||  NULL  ||   NULL    ||
___________________________________________________

之后 SQL 语句应该已经更新为,或max_value的最大值。像这样:value1value2value3

___________________________________________________
|| id || value1 || value2 || value3 || max_value ||
___________________________________________________
|| 1  ||    1   ||   2    ||   3    ||     3     ||
===================================================
|| 2  ||    99  ||   2    ||   3    ||     99    ||
===================================================
|| 3  ||    1   ||   66   ||   66   ||     66    ||
===================================================
|| 4  ||    1   ||   2    ||  NULL  ||     2     ||
===================================================
|| 5  ||  NULL  ||  NULL  ||  NULL  ||   NULL    ||
___________________________________________________

谁能给我一个 MySQL 查询?

4

3 回答 3

5

您必须用您喜欢的值或任何值替换NULL0,否则与“未知值”的比较总是返回“未知值”。

update table1 
set max_value = greatest(coalesce(value1, 0), coalesce(value2, 0), coalesce(value3, 0));

coalesce()函数返回其第一个参数,即not null

于 2013-08-08T09:47:51.887 回答
4

GREATEST不会NULL以您需要的方式进行交互,但是UPDATE/JOIN会在没有太多复杂性的情况下进行交互;

UPDATE Table1 t1
JOIN (
  SELECT id,MAX(value) value FROM (  
    SELECT id,value1 value FROM Table1 UNION ALL 
    SELECT id,value2       FROM Table1 UNION ALL
    SELECT id,value3       FROM Table1
  ) g GROUP BY id
) a ON t1.id = a.id
SET t1.max_value=a.value;

一个用于测试的 SQLfiddle

于 2013-08-08T09:56:33.453 回答
0
UPDATE mytable, (SELECT id,
    CASE
        WHEN value1>= value2 AND value1 >= value3 THEN value1
        WHEN value2 >= value1 AND value2 >= value3 THEN value2
        WHEN value3 >= value1 AND value3 >= value2 THEN value3        
    END AS value FROM mytable) ans 
  SET max_value = ans.value where ans.id=mytable.id ;
于 2013-08-08T10:03:57.287 回答