r/SQL • u/winstr12 • 10h ago
MySQL [MySQL] I'm doing a personal project and need help with importing a large amount of CSV files (+1000)
I have a dataset about football statistics, 3 years worth of data.
There are 38 gameweeks per season so 3x38.
In each gameweek folder there are 10 different csv files with various stats (fixtures.csv, matches.csv, playerstats.csv etc...)
Each of those 10 csv files have the same structure (columns and column names) in each season and in each gameweek.
So the playerstats.csv from season 1, gameweek 10 is the same structure as playerstats.csv from season 3, gameweek 2, and the same applies for the 9 other csv types.
What I want is to import all "playerstats.csv" files from all seasons 1-3, and all gameweeks from those seasons 3x38 into one table, the same goes for the other 9 unique csv types.
How does one do that?
I know I can use AI and speed up things, but I'm still learning and want to do everything by myself to improve my sql knowledge.
I know how to import a csv file, I know how to create tables... but I do not want to import 3x38x10 = 1140 csv files manually and I've never done a project with this many csv files.
The only thing that has popped to my mind is a recursive cte?
I hope I clarified my question.
Thank you
5
u/NW1969 10h ago
Assuming all the files for each target table are in a dedicated folder then just write a script (PowerShell, bash, etc) to loop through the files and run the MySQL import statement for each one.
A quick search will provide loads of examples for how to do this
2
u/t1nkl 6h ago
you don't need to move anything into separate folders, a loop can walk your existing season/gameweek folders and pick only playerstats.csv from each. the part people skip: once all 114 files are in one table you can't tell which week a row came from, so take season and gameweek from the folder names and store them in every row:
LOAD DATA LOCAL INFILE '<path>' INTO TABLE playerstats FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' IGNORE 1 LINES (player, goals, ...) SET season = 1, gameweek = 10
the column list in brackets is the csv's columns in order, SET fills the extra ones. the loop just puts the numbers from the path in there. keep the ENCLOSED BY part, without it a quoted value with a comma like "Smith, J" gets split into two columns, and with LOCAL that's only a warning, so bad rows go in silently. run SHOW WARNINGS after the first file.
two things that will bite on the first run. LOCAL is off by default in mysql 8+, you get "Loading local data is disabled; this must be enabled on both the client and server sides". so SET PERSIST local_infile = 1 on the server (SET GLOBAL is lost on restart) and start the client with --local-infile=1. and if the loop calls mysql -p, it asks for the password once per file, 1140 times. either put the credentials in ~/.my.cnf, or have the loop write all the LOAD DATA lines into one .sql file and run that once with mysql --local-infile=1 < load.sql, which is also easier to check before you run it.
if the files came from windows and the last column is text, it will end with a hidden \r, add LINES TERMINATED BY '\r\n'.
1
u/Discordbothost 9h ago
Every gameweek has a playerstats.csv, so the filename alone won't identify where a row came from. I'd keep season and gameweek from the folder path and test with two weeks first.
1
u/Thanael124 7h ago
Welcome to ETL ingest. Write a small script, ai can help.
Maybe the import wozard works on folders too, then you would not even need that. 1 folder per table…
1
u/baubleglue 7h ago
Do you know any programming language except SQL?
1
u/Either-Surprise6390 4h ago
I wouldn't tackle this in SQL. I'd write a program that stitches the like CSV files together, so you're left with the 10 files, one for each table. then load them in. Here's something similar written in Winbatch for something I used semi-recently, in July... Of course you'd need the Winbatch compiler to convert it into an EXE file. This specifically takes a set of files in Directory "A" and another set of files in Directory "B" and merges the files together and puts them into Directory "C". I think the use case is two separate data sets were coming from two systems, but we wanted to merge the two datasets for a single file capturing all of the records.
; ==============================================================================
; WinBatch CSV Merger Script (Headless / Scheduled Task Version)
; ==============================================================================
; TODO: Update these paths once your SFTP server directories are established.
; CRITICAL: Ensure all directory paths end with a trailing backslash (\).
dirA = "C:\A\"
dirB = "C:\B\"
dirC = "C:\C\"
logPath = dirC : "merge_log.txt"
; Comma-delimited list of target files
fileList = "schools.csv,students.csv,teachers.csv,sections.csv,enrollments.csv,staff.csv"
fileCount = ItemCount(fileList, ",")
; Open the log file for appending immediately
logHan = FileOpen(logPath, "APPEND")
FileWrite(logHan, "[" : TimeCurrent() : "] --- Script Execution Started ---")
allSuccessful = u/TRUE
; Loop through each file in the list
For i = 1 To fileCount
currentFile = ItemExtract(i, fileList, ",")
pathA = dirA : currentFile
pathB = dirB : currentFile
pathC = dirC : currentFile
; Check if both source files are present
If FileExist(pathA) && FileExist(pathB)
; 1. Copy File A to Directory C (Overwrite allowed via u/FALSE)
FileCopy(pathA, pathC, u/FALSE)
; 2. Open File B for reading and File C for appending
fileHanB = FileOpen(pathB, "READ")
fileHanC = FileOpen(pathC, "APPEND")
; 3. Skip the header row of File B
FileRead(fileHanB)
; 4. Append data lines from File B into File C
While u/TRUE
line = FileRead(fileHanB)
If line == "*EOF*" Then Break
FileWrite(fileHanC, line)
EndWhile
; Close data file handles
FileClose(fileHanB)
FileClose(fileHanC)
Else
; Log exactly which file pair failed (Failsafe logic)
allSuccessful = u/FALSE
If !FileExist(pathA) Then FileWrite(logHan, "[" : TimeCurrent() : "] ERROR: Missing " : currentFile : " in Directory A.")
If !FileExist(pathB) Then FileWrite(logHan, "[" : TimeCurrent() : "] ERROR: Missing " : currentFile : " in Directory B.")
EndIf
Next
; Final execution log entry
If allSuccessful
FileWrite(logHan, "[" : TimeCurrent() : "] SUCCESS: All available CSV files have been merged into Directory C.")
Else
FileWrite(logHan, "[" : TimeCurrent() : "] WARNING: Merge completed with missing files. Check errors above.")
EndIf
; Close the log file and exit smoothly
FileClose(logHan)
Exit
1
u/stantaneous 3h ago
love that you want to do this one yourself, great project to learn on.
i'd get just playerstats working first, with season and gameweek saved on every row.
then group by those two and count. you should see 114 groups, so if a week didn't load you'll spot it right away.
1
u/thetwoweeks 2h ago
A very simplified way of doing it. Copy all the csv files with the same structure using the Windows command shell to one file... copy *.csv output.csv. If there are headers, you'll need to remove the duplicate headers.