Last active
July 15, 2022 05:36
-
-
Save gaerae/6219678 to your computer and use it in GitHub Desktop.
MySQL Table의 데이터를 CSV 형태로 내보내기 방법에는 여러가지가 있습니다.어떤 방법으로만 해야된다가 아닌 상황에 맞게 사용하는게 좋을 거 같습니다.4 가지 예시입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT * FROM my_table | |
INTO OUTFILE 'my_table.csv' | |
CHARACTER SET euckr | |
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' | |
ESCAPED BY '\\' | |
LINES TERMINATED BY '\n' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT * FROM ( | |
( | |
SELECT | |
'필드1' AS 'filed_1', | |
'필드2' AS 'filed_2' | |
) UNION ( | |
SELECT | |
filed_1, | |
filed_2 | |
FROM my_table | |
) | |
) AS mysql_query | |
INTO OUTFILE 'my_table.csv' | |
CHARACTER SET euckr | |
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' | |
ESCAPED BY '\\' | |
LINES TERMINATED BY '\n' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mysql -p my_db -e "SELECT * FROM my_table" | sed 's/\t/","/g;s/^/"/;s/$/"/;' > my_table.csv |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
db=YOUR_DB | |
user=YOUR_USER | |
pass=YOUR_PASS | |
for table in $(mysql -u$user -p$pass $db -Be "SHOW tables" | sed 1d); do | |
echo "exporting $table.." | |
mysql -u$user -p$pass $db -e "SELECT * FROM $table" | sed 's/\t/","/g;s/^/"/;s/$/"/;' > $table.csv | |
done |
@kampores 님이 잘 못된 부분을 잘 수정해주셨네요. 본문 내용을 수정했습니다.
감사합니다.
저는 mysql 8를 사용 중입니다.
1번 쿼리를 사용해보니 'my_table.csv' 파일명에 my.ini의 secure-file-priv 경로를 같이 적어야 정상적으로 파일이 export 되네요.
데이터 건 수(몇 십만건)가 많을 경우에는 3번 방법을 사용하면 안될 것 같아요. 데이터 건마다 치환 작업을 해주어야 하니 오랜 시간이 걸립니다.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
스크립트 감사합니다. 3번의 경우는 안되는데
mysql -p my_db -e "SELECT * FROM my_table" | sed 's/\t/","/g;s/^/"/;s/$/"/;' > my_table.csv
이 맞는것 같습니다.