使用所选行的值设置所有行的值
Set values of all rows with the value of selected row
所以我 table 是这样的:
+----+-------+-----+
| id | name | ... |
+----+-------+-----+
| 1 | test1 | ... |
| 2 | test2 | ... |
| 3 | test3 | ... |
| 4 | test4 | ... |
+----+-------+-----+
我想要的是它们都具有相同的name
,例如test2
,这取决于id
。 我不想要解决方案,我手动写入该值。 所以当我输入数字 2
时,它会将所有行的名称更改为 test2
,因为id = 2 is test2
.
我试过这个命令:
UPDATE table SET name = t.name SELECT t.* FROM table AS t WHERE id = 2;
我期望的解决方案是:
+----+-------+-----+
| id | name | ... |
+----+-------+-----+
| 1 | test2 | ... |
| 2 | test2 | ... |
| 3 | test2 | ... |
| 4 | test2 | ... |
+----+-------+-----+
PS: 我的table没有那个名字,结构也完全不同,但是我用这个jsut做例子。
Update table SET name =
(Select name
from table
where id = 2)
如果这在 MySQL 中不起作用,那么试试这个
Update t SET name =
(Select name
from table
where id = 2)
From table t
OP 发现的 MariaDB 的正确语法:
UPDATE table as t,
(SELECT name FROM table
WHERE id = 2) as temp
SET t.name = temp.name
没有更好,但也许不那么神秘:
SELECT @thename := name FROM table WHERE id = 2;
UPDATE table SET name = @thename;
所以我 table 是这样的:
+----+-------+-----+
| id | name | ... |
+----+-------+-----+
| 1 | test1 | ... |
| 2 | test2 | ... |
| 3 | test3 | ... |
| 4 | test4 | ... |
+----+-------+-----+
我想要的是它们都具有相同的name
,例如test2
,这取决于id
。 我不想要解决方案,我手动写入该值。 所以当我输入数字 2
时,它会将所有行的名称更改为 test2
,因为id = 2 is test2
.
我试过这个命令:
UPDATE table SET name = t.name SELECT t.* FROM table AS t WHERE id = 2;
我期望的解决方案是:
+----+-------+-----+
| id | name | ... |
+----+-------+-----+
| 1 | test2 | ... |
| 2 | test2 | ... |
| 3 | test2 | ... |
| 4 | test2 | ... |
+----+-------+-----+
PS: 我的table没有那个名字,结构也完全不同,但是我用这个jsut做例子。
Update table SET name =
(Select name
from table
where id = 2)
如果这在 MySQL 中不起作用,那么试试这个
Update t SET name =
(Select name
from table
where id = 2)
From table t
OP 发现的 MariaDB 的正确语法:
UPDATE table as t,
(SELECT name FROM table
WHERE id = 2) as temp
SET t.name = temp.name
没有更好,但也许不那么神秘:
SELECT @thename := name FROM table WHERE id = 2;
UPDATE table SET name = @thename;