1

I have a table Table1 which has data like

-------------------------------
code     value
-------------------------------
02      null
05      null
06      hi
02      hello
05      how

I want to update the same table as

-------------------------------
id     value
-------------------------------
02      hello
05      how
06      hi
02      hello
05     how

I used the following query, but is not working:

update Table1 set value=value where id is null
Tom
  • 1,387
  • 3
  • 19
  • 30
Intact Abode
  • 382
  • 5
  • 20

5 Answers5

4

You need to create alias of the Table1 and than set value into null record as below:

UPDATE Table1 t1, (
  SELECT DISTINCT id, value 
  FROM Table1 
  WHERE value IS NOT NULL AND value != ''
) t2 SET t1.value = t2.value 
WHERE t1.id = t2.id;

Above query is tested and working.

GuRu
  • 1,880
  • 3
  • 23
  • 32
Atul Kamani
  • 105
  • 6
0

You need a join to connect the two tables (correlated subqueries are tricky in MySQL update statements):

update table1 t1 join
       (select id, min(value) as value
        from table1
        group by id
       ) tt1
       on t1.id = tt.id
    set t1.value = tt1.value
    where t1.value is null;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

I think there was a simpler syntax:

update t1 from table1 t1, table2 t2 set t1.value=t2.value where t1.code=t2.id

Tho I havent tested it right now.

Tuncay Göncüoğlu
  • 1,699
  • 17
  • 21
  • For this specific example, this may well be correct, but I don't think this solution scales up to a more general answer. – Strawberry Aug 03 '17 at 11:58
-1

Query should be written as:

update Table1 set value=' ' where id = 1.

Here value is the column name and you like to update some content(hi, hello etc) to it. If the content is String, then enclose it with single/double quotes. For what row you want to update that comes after WHERE clause. Here you are setting condition as WHERE id = 1. So for id =1, the value gets updated.

  • It looks like the question may be worded incorrectly for the results they're after. The only difference between before and after I can see is that the 'code' column has become an 'id' column. Instead of an update I think the user is after an alter table statement. – Paul Aug 03 '17 at 12:02
-1

Generate a script with a SELECT statement and execute it (don't forget commit at the end):

select concat('update Table1 set value=`', value, '` where id =', id, ';') as script from Table1 where value is not null;
witchi
  • 345
  • 3
  • 16