我有下表
#key | #value
colour | red
weather | blue
现在我想用关键颜色更新行的值,使其成为具有关键天气的行的值。所以我在做:
UPDATE table_name
SET value = (SELECT value FROM table_name WHERE key = "weather")
WHERE key = "colour";
但此更新给出了以下错误消息:
您无法在FROM子句
中指定要更新的目标表
如何在没有错误的情况下执行该查询?
答案 0 :(得分:1)
这可能是因为select
查询可能会为列value
UPDATE table_name
SET value = (SELECT max(value) FROM table_name WHERE key = "weather")
WHERE key = "colour";
或
UPDATE table_name
SET value = (SELECT value FROM table_name WHERE key = "weather" limit 1)
WHERE key = "colour";
您可以尝试通过使用table_name
替换子查询中的(SELECT * FROM table_name)
实例来更改此内容:
UPDATE table_name
SET table_name.A =
(
SELECT B
FROM (SELECT * FROM table_name) AS something
INNER JOIN ...
)
同时检查How to select from an update target in MySQL
您不希望在子查询中实际选择SELECT * FROM表 生活;我只是想让这些例子保持简单。实际上你应该 只能在最里面的查询中选择所需的列,并且 添加一个好的WHERE子句来限制结果。
编辑: -
正如您已经评论过的那样,但我上面已经回答过使用这样的临时表: -
UPDATE table_name
SET value = (SELECT value FROM (SELECT value FROM table_name WHERE key="weather") AS x)
WHERE key="colour"
答案 1 :(得分:0)
如果你的sql支持'LIMIT'
,你可以试试这个UPDATE table_name SET value = (SELECT value FROM table_name WHERE key = "weather" LIMIT 1 ) WHERE key = "colour";
答案 2 :(得分:-1)
UPDATE table_name
SET colour ='red',weather =blue
WHERE column_name = some_value;
答案 3 :(得分:-1)
这不会那样。对于同一个表,您不能同时具有读取和写入查询。有两个不同的表,它将起作用。
UPDATE `table` SET value = (SELECT value FROM `Table_b` WHERE `other_value` = 'xy' LIMIT 1) WHERE `key` = 'colour'