Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

mysql - Import CSV to Update rows in table

There are approximately 26K products (posts) and each product has meta values like this:

enter image description here

The post_id column is the product id in db and the _sku (meta_key) is the unique id for each product.

I've received a new CSV file that updates all of the values (meta_value) for _sale_price (meta_key) of each product. The CSV file looks like:
SKU, Sale Price

How do I import this CSV to update only the _sale_price row based on the post_id (product id) & _sku value?

Output Example:

enter image description here

I know how to do this in PHP by looping through the CSV and selecting & executing an update for each single product but this seems inefficient.

Preferably with phpMyAdmin and by using LOAD DATA INFILE.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use temporary table to hold the update data and then run single update statement.

CREATE TEMPORARY TABLE temp_update_table (meta_key, meta_value)

LOAD DATA INFILE 'your_csv_pathname' 
INTO TABLE temp_update_table FIELDS TERMINATED BY ';' (meta_key, meta_value); 

UPDATE "table"
INNER JOIN temp_update_table on temp_update_table.meta_key = "table".meta_key
SET "table".meta_value = temp_update_table.meta_value;

DROP TEMPORARY TABLE temp_update_table;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...