简体   繁体   中英

php mysql update all fields

Sorry for asking a trivial question. I want to translate some of the fields of my database which has one million rows. So what I want to do is to read field 1 and perform the translate function and write it to field 3 and respectively field 2 needs to be written into field 4.

initial table field id|field 1 |field 2 |field 3|field 4|
1 | apple | pear | empty |empty |
2 | banana | pineapple | empty |empty |

end result table translate(apple) - yabloko

field id|field 1 |field 2 |field 3|field 4|
1 | apple | pear | yablogo |grusha |
2 | banana | pineapple | banan |ananas |

I already have the translate function, the question is how to perform this on all one million rows. How to construct the loop through it correctly? (surely there are some IDs missing, as some of the data was removed).

thank you so much in advance!!!

Rather than "construct a loop" and process row by row, the normative pattern would be to perform the operation in a single statement.

I'd populate a translation table:

CREATE TABLE my_translation
( old_word VARCHAR(100) NOT NULL PRIMARY KEY
, new_word VARCHAR(100)
) Engine=InnoDB;
INSERT INTO my_translation (old_word, new_word) VALUES
 ('apple'    ,'yablogo')
,('pear'     ,'grush')
,('banana'   ,'banan')
,('pineapple','ananas);

Then do an update. The tricky part is leaving field_3 and field_4 unmodified if there's no match.

UPDATE my_table t
  LEFT 
  JOIN my_translation c3
       ON c3.old_word = t.field_1
  LEFT 
  JOIN my_translation c4
       ON c4.old_word = t.field_2
   SET t.field_3 = IF(c3.old_word IS NULL,t.field_3,c3.new_word)
     , t.field_4 = IF(c4.old_word IS NULL,t.field_4,c4.new_word)

NOTE: If this is a one-time operation, I might consider doing this as an INSERT into a new table, and then swapping the table names and changing foreign key references, to put the new table in place of the old table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM