mysql 输出结果到本地文件中的方法
语法: mysql -e "select statement" > file.csv
注意点: 使用特殊符号分隔不同的filed,使用 IFNULL 函数对 null 做处理。
用 CONCAT_WS 函数:
CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string, as can the rest of the arguments. If the separator is NULL, the result is NULL.
mysql> SELECT CONCAT_WS(',','First name','Second name','Last Name');
-> 'First name,Second name,Last Name'
mysql> SELECT CONCAT_WS(',','First name',NULL,'Last Name');
-> 'First name,Last Name'
CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2.
例子:
mysql -h 127.0.0.1 -P 3324 -u root -proot -e "SELECT CONCAT_WS('\\u01',
IFNULL(cdt,'-'),
IFNULL(active,'-'),
IFNULL(leuid_active,'-')) FROM bigdata_data_market.tdm_phone_active_daily
where cdt='20150530'" > tdm_phone_active_daily_20150530.csv
mysql -e "select CONCAT_WS('\\u01',IFNULL(id,'-'),IFNULL(tpl_name,'-'),IFNULL(tpl_path,'-')) from zhan.mo_remind" > 'mo_remind.csv'
mysql -e "select CONCAT_WS('\\u01',IFNULL(id,'-'),IFNULL(null,'-')) from zhan.mo_remind" > 'mo_remind.csv'