开发者

How to copy text column value from one row to another row in mySQL

开发者 https://www.devze.com 2023-02-05 17:22 出处:网络
I have table pref havin开发者_JAVA技巧g column value. This value has type text. I want copy the value field value of row with id 7 to the value field of row with id 1. Can you please help how to do th

I have table pref havin开发者_JAVA技巧g column value. This value has type text. I want copy the value field value of row with id 7 to the value field of row with id 1. Can you please help how to do this. I know MS SQL, but I am new to mySQL.

create table pref
(
   id int,
   value text
)


In MySQL you can't use a subselect from the same table you are updating, but you can use a join.

   UPDATE pref AS target
LEFT JOIN pref AS source ON source.id = 7
      SET target.value = source.value
    WHERE target.id = 1;


UPDATE
    pref
SET
    value = (SELECT value WHERE id = 7)
WHERE
    id = 1


In my case, I was trying to copy an encrypted value from one row into an empty field in another row in the same table. In this case, I needed to copy john's PIN into Jane's PIN.

@mohang has it right. Here is my adaptation :)

name   pin

john   sdhjduwhdowodw7d87e838g83g8g3of...
jane       

    //copy from field with value into empty field

UPDATE my_table AS target
LEFT JOIN my_table AS source ON source.pin != ""
SET target.pin = source.pin
WHERE target.pin = "";

    // Hurray, it works!

name   pin

john   sdhjduwhdowodw7d87e838g83g8g3of...
jane   sdhjduwhdowodw7d87e838g83g8g3of...   
0

精彩评论

暂无评论...
验证码 换一张
取 消