0
$\begingroup$

So I have table like this:

+----+-------+-----+
| id | name  | ... |
+----+-------+-----+
| 1  | test1 | ... |
| 2  | test2 | ... |
| 3  | test3 | ... |
| 4  | test4 | ... |
+----+-------+-----+

What I want is that all of them will have same name, for example test2, it depends on the id. I don't want solution, where I manually write that value. So when I entered number 2, it will change all row's name to the test2, because id = 2 is test2.

I tried this command:

UPDATE table SET name = t.name SELECT t.* FROM table AS t WHERE id = 2;

My expecting solution would be:

+----+-------+-----+
| id | name  | ... |
+----+-------+-----+
| 1  | test2 | ... |
| 2  | test2 | ... |
| 3  | test2 | ... |
| 4  | test2 | ... |
+----+-------+-----+

PS: my table haven't got that name, also structure is completely different, but I have used this jsut for the example.

$\endgroup$
1
  • $\begingroup$ provide us with an sql fiddle, this way it's much easier for people to test their possible solutions $\endgroup$ Commented Aug 30, 2016 at 13:30

2 Answers 2

3
$\begingroup$
Update table SET name =
   (Select name 
    from table 
    where id = 2)

if this does not work in MySQL, then try this

Update t SET name =
   (Select name 
    from table 
    where id = 2)
From table t

Correct syntax for MariaDB as discovered by OP:

UPDATE table as t, 
     (SELECT name FROM table 
      WHERE id = 2) as temp
  SET t.name = temp.name
$\endgroup$
Sign up to request clarification or add additional context in comments.

5 Comments

#1093 - Table 'table' is specified twice, both as a target for 'UPDATE' and as a separate source for data
Yes.. -------------- So? This is perfectly fine. Does it not work in MySQL ?
Ooh, sorry, I made a mistake :) I don't have MySQL, but MariaDB. I have MySQL on the another computer. It seems like that ALIAS is not working in the MariaDB. But it works in the SELECT.
Sorry, I am not familiar with MariaDB, can't help you with syntax for that product, especially if its not standard SQL.
Well, I have found a solution :) So the command for the MariaDB would be like this (also you can enter it into your answer, so it will be more visible): UPDATE table as t, (SELECT name FROM table WHERE id = 2) as temp SET t.name = temp.name
1
$\begingroup$

No better, but perhaps less cryptic:

SELECT @thename := name  FROM table  WHERE id = 2;
UPDATE table  SET name = @thename;
$\endgroup$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.