DBSQL Insert value from one entity in a column to another in different column

时间:2015-07-31 19:20:44

标签: mysql

can u guys tell me if this is correct?? i am trying to insert the value of firstname_1 into first_name.

INSERT INTO wp_usermeta(meta_value) where meta_key=first_name
select meta_value where meta_key=firstname_1

THIS IS THE TABLE (tablename = wp_usermeta) VIEW FROM THE DATABASE

423 16 firstname_1 vrigu
424 16 lastname_2 de
425 16 gender_5 male
426 16 bankname_3 SBI
427 16 accountnumber_4 9456874526
429 17 nickname mithu123
430 17 first_name
431 17 last_name

1 个答案:

答案 0 :(得分:0)

If you want to insert a new row, you use this:

INSERT INTO wp_usermeta (user_id, meta_key, meta_value)
SELECT user_id, 'first_name', meta_value
FROM wp_usermeta
WHERE meta_key = 'firstname_1'

If you want to fill in an existing row, you use UPDATE, not INSERT:

UPDATE wp_usermeta AS t1
JOIN wp_usermeta AS t2 ON t1.user_id = t2.user_id
SET t1.meta_value = t2.meta_value
WHERE t1.meta_key = 'first_name'
AND t2.meta_key = 'firstname_1'

If you need to do both -- update the row if it already exists, or create a new row -- you can use INSERT with the ON DUPLICATE KEY UPDATE option:

INSERT INTO wp_usermeta (user_id, meta_key, meta_value)
SELECT user_id, 'first_name', meta_value
FROM wp_usermeta
WHERE meta_key = 'firstname_1'
ON DUPLICATE KEY UPDATE meta_value = VALUES(meta_value);

This assumes there's a unique index on the composite key (user_id, meta_key)