我有一个mysql表如下:
name | serialno | key
---------------------
NULL | NULL | 10
luke | 1234 | 20
NULL | NULL | 30
NULL | NULL | 40
我必须更新有效密钥name
和serialno
更新的行。
我正在运行的更新语句如下:
UPDATE test SET Name = 'pc', Serialno = '10', WHERE `Key` = '10' AND name is null
和
UPDATE test SET Name = CASE
WHEN NULL THEN 'pc'
END
SET Serialno = CASE
WHEN NULL THEN '10'
END
Where `key` = '20'
显示以下错误:
1
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 'WHERE Key = '10' AND name is null' at line 1:
2
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 'SET Serial = CASE
WHEN NULL THEN '10'
END
Where `key`='20'' at line 4:
请帮忙。
答案 0 :(得分:0)
UPDATE test SET Name = CASE Name
WHEN NULL THEN 'pc'
END,
SET Serialno = CASE Serialno
WHEN NULL THEN '10'
END
Where `key` = '20'
您必须指定CASE的条件
答案 1 :(得分:0)
我不知道上下文是什么(你能解释你想要的细节,然后我会帮助你获得更好的结果)。
然而,正如StanislavL的回答,语法错误。我更正了如下:
UPDATE test SET Name = CASE Name
WHEN NULL THEN 'pc'
END,
Serialno = CASE Serialno
WHEN NULL THEN '10'
END
Where `key` = '20'
答案 2 :(得分:0)
错误的原因:
错误1 是因为您在,
之前有一个WHERE Key = '10' ...
逗号。
声明应该是:
UPDATE test SET Name = 'pc', Serialno = '10' WHERE `Key` = '10' AND name is null
错误2 是因为您没有指示要检查哪个案例值 when
子句。可接受的语法是:
1. CASE column_name WHEN value THEN expr1 ELSE expr2 END
2. CASE WHEN column_name <condition> value THEN expr1 ELSE expr2 END
声明应该是:
UPDATE test
SET
Name = CASE WHEN name IS NULL THEN 'pc' else name end
, Serialno = CASE WHEN serialno IS NULL THEN '10' else serialno end
END
Where `key` = '10'
示例 @ SQL Fiddle
您可以对此进行扩展,以根据不同的key
值设置列的值,而不使用where
子句。
示例:
UPDATE test
SET
Name = CASE WHEN `key`=10 and name IS NULL THEN 'pc' else name end
, Serialno = CASE WHEN `key`=10 and serialno IS NULL THEN '10' else serialno end
, Name = CASE WHEN `key`=30 and name IS NULL THEN 'key is 30' else name end
, Serialno = CASE WHEN `key`=30 and serialno IS NULL THEN '3' else serialno end
END
答案 3 :(得分:0)
请这样做
UPDATE test SET Name = 'pc', Serialno = '10' WHERE `Key` = '10' AND name is null