8

我正在尝试在 MySQL 中执行以下操作:

UPDATE
    x
SET
    y = COALESCE(SELECT z FROM table WHERE a = b AND c = d AND e = f LIMIT 1,
                 SELECT z FROM table WHERE a = b AND c = d LIMIT 1,
                 SELECT z FROM table WHERE a = b LIMIT 1);

这对我来说听起来很有效。我正在尝试使用最合适的值更新列。如果我能找到符合 3 个条件的记录 -> 那就是我需要的。否则一个适合 2 个标准,否则一个记录只匹配一个标准。

我可以在 3 个更新查询中做到这一点,但我不明白为什么这不起作用。根据手册

COALESCE returns the first non-NULL value in the list, or NULL if there are no non-NULL values.

正是我需要的。但它给出了以下错误:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT'

我在这里错过了什么吗?

4

2 回答 2

9

您的问题可能是子选择返回的 z 值超过 1 个。你只能得到一个。

你可以试试:

update x
set y = (select z from t where a = b
         order by (case when a = b and c = d and e = f then 1
                        when a = b and c = d then 2
                        else 3
                   end)
         limit 1
        );

但是,您的特定语法错误是您需要在选择周围加上括号。所以这是语法正确的版本:

UPDATE
    x
SET
    y = COALESCE((SELECT z FROM table WHERE a = b AND c = d AND e = f LIMIT 1),
                 (SELECT z FROM table WHERE a = b AND c = d LIMIT 1),
                 (SELECT z FROM table WHERE a = b LIMIT 1));
于 2013-03-26T13:14:23.520 回答
1

没有更多细节很难给出建议,但这样的事情可能会奏效

UPDATE
    x
SET y = COALESCE(
    ( SELECT z FROM table WHERE a = b AND c = d AND e = f LIMIT 1),
    ( SELECT z FROM table WHERE a = b AND c = d LIMIT 1 ),
    ( SELECT z FROM table WHERE a = b LIMIT 1 )
);

确保每个子查询最多只返回 1 行。

于 2013-03-26T13:15:40.007 回答