我有两张桌子:
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
我需要将得分历史数据(数千行)批量插入table_score。历史数据仅包括UserName,Date和Score。
我正在做的是让我的PHP脚本从MySQL加载给定UserName的UID,将UID添加到批量插入SQL并将其发送回MySQL。这需要PHP和MySQL之间的2次通信。我再为其他用户重复上述内容。
是否可以让MySQL插入日期和分数,并在一个SQL中根据给定的UserName自动填写UID?
答案 0 :(得分:0)
为MySql导入大量数据的最快方法是使用LOAD DATA INFILE
如果你有像这样的昏迷分隔文件
"UserB","18/7/2013",100 "UserB","19/7/2013",150 "UserC","20/7/2013",140
然后用这样的查询
加载它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;