I have two tables:
table_user
======================================
UID UserName
1 UserA
2 UserB
3 UserC
table_score
==============================
UID Date Score
2 18/7/2013 100
2 19/7/2013 150
I need to bulk insert score history data (thousands of rows) to table_score. The history data consists of UserName, Date and Score only.
What I'm doing is to have my PHP script load the UID of a given UserName from MySQL, add the UID in to the bulk insert SQL and send it back to MySQL. This requires 2 communications between PHP and MySQL. And I repeat the above for another user.
Is it possible to let MySQL insert the date and score, and fill-in the UID automatically based on the given UserName in one SQL?
The fastest method to import massive amount of data for MySql is to use LOAD DATA INFILE
If you were to have a coma delimited file like this
"UserB","18/7/2013",100 "UserB","19/7/2013",150 "UserC","20/7/2013",140
Then you load it with a query like this
LOAD DATA LOCAL INFILE '/path/to/your/file.csv'
INTO TABLE table_score
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n' -- or '\r\n' if it's Windows
(@username, @date, @score)
SET uid =
(
SELECT uid
FROM table_user
WHERE username = @username
LIMIT 1
),
date = STR_TO_DATE(@date, '%d/%m/%Y'),
score = @score;
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.