私はかなり定期的にこの正確な問題を探しているので(以前に何かを見逃したことを期待して...)、ついに時間をかけて、MySQLクエリをCSVファイルとしてエクスポートするための小さな要点を書くことにしました。 /stackoverflow.com/a/28168869ですが、PHPに基づいており、さらにいくつかのオプションがあります。これは私のユースケースにとって重要でした。CSVパラメータ(区切り文字、NULL値の処理)を微調整できる必要があり、ファイルは実際に有効なCSVである必要があるため、単純CONCAT
では不十分であるため、単純では不十分です。値に改行またはCSV区切り文字が含まれている場合は、有効なCSVファイルを生成します。
注意:サーバーにPHPがインストールされている必要があります。
(で確認できますphp -v
)
mysql2csv
経由で「インストール」
wget https://gist.githubusercontent.com/paslandau/37bf787eab1b84fc7ae679d1823cf401/raw/29a48bb0a43f6750858e1ddec054d3552f3cbc45/mysql2csv -O mysql2csv -q && (sha256sum mysql2csv | cmp <(echo "b109535b29733bd596ecc8608e008732e617e97906f119c66dd7cf6ab2865a65 mysql2csv") || (echo "ERROR comparing hash, Found:" ;sha256sum mysql2csv) ) && chmod +x mysql2csv
(要点の内容をダウンロードし、チェックサムを確認して実行可能にします)
使用例
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"
/tmp/result.csv
コンテンツを含むファイルを生成します
foo,bar
1,2
参考のためのヘルプ
./mysql2csv --help
Helper command to export data for an arbitrary mysql query into a CSV file.
Especially helpful if the use of "SELECT ... INTO OUTFILE" is not an option, e.g.
because the mysql server is running on a remote host.
Usage example:
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"
cat /tmp/result.csv
Options:
-q,--query=name [required]
The query string to extract data from mysql.
-h,--host=name
(Default: 127.0.0.1) The hostname of the mysql server.
-D,--database=name
The default database.
-P,--port=name
(Default: 3306) The port of the mysql server.
-u,--user=name
The username to connect to the mysql server.
-p,--password=name
The password to connect to the mysql server.
-F,--file=name
(Default: php://stdout) The filename to export the query result to ('php://stdout' prints to console).
-L,--delimiter=name
(Default: ,) The CSV delimiter.
-C,--enclosure=name
(Default: ") The CSV enclosure (that is used to enclose values that contain special characters).
-E,--escape=name
(Default: \) The CSV escape character.
-N,--null=name
(Default: \N) The value that is used to replace NULL values in the CSV file.
-H,--header=name
(Default: 1) If '0', the resulting CSV file does not contain headers.
--help
Prints the help for this command.