[英]mysql bulk insert referring ID from another table
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. 我需要将得分历史记录数据(数千行)批量插入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. 我正在做的是让我的PHP脚本从MySQL加载给定UserName的UID,将UID添加到批量插入SQL中,然后将其发送回MySQL。 This requires 2 communications between PHP and MySQL.
这需要PHP和MySQL之间进行2次通信。 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? 是否可以让MySQL插入日期和分数,并在一个SQL中根据给定的UserName自动填写UID?
The fastest method to import massive amount of data for MySql is to use LOAD DATA INFILE
为MySql导入大量数据的最快方法是使用
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.