如何使用php函数将mysql查询输出为csv改变列值

im9ewurl  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(452)

我试图将我的表数据导出到csv,但我需要使用比较php数组或函数来更改列值。
我正在尝试,而循环,但它需要很多时间和内存问题使。
我的问题

SELECT column,$conversionServiceId[column2],column3
 INTO OUTFILE '/path/to/file/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM yourtable WHERE columnx = 'çondition';

$conversionServiceId = [
    'green'=>'1',
    'yellow'=>'2',
    'red'=>'3'
];

第2列值选择自 $conversionServiceId 数组
我不知道如何选择窗体数组。我有超过10万行

t9eec4r0

t9eec4r01#

你不能这样把php和sql混在一起。您可以先用sql下载文件,然后打开并用php修改它,或者将转换逻辑移到sql查询本身。
显然,第二种解决方案更有效。
如果转换列表较小,则 CASE (或cte)应:

SELECT 
    column,
    CASE 
        WHEN column2 = 'green'  THEN 1
        WHEN column2 = 'yellow' THEN 2
        WHEN column2 = 'red'    THEN 3
    END column2
    column3
INTO 
    OUTFILE '/path/to/file/result.txt'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM yourtable 
WHERE columnx = 'çondition';

如果要处理一个大的转换列表,可以考虑将其存储在数据库表中。假设您的转换表被称为 yourconversiontable 并且有列 old 以及 new ,然后:

SELECT 
    t.column,
    c.new
    t.column3
INTO 
    OUTFILE '/path/to/file/result.txt'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM yourtable t
INNER JOIN yourconversiontable c ON t.column2 = c.old
WHERE t.columnx = 'çondition';
3htmauhk

3htmauhk2#

一个有效的例子:

<?php
$con=mysqli_connect("localhost","user","password","db_name");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Your array 
$conversionServiceId = [
    'green'=>'column1',
    'yellow'=>'column2',
    'red'=>'column3'
];

$qstring = "
SELECT id," . $conversionServiceId['green'] . "
  INTO OUTFILE 'e:/result.csv'
  FIELDS TERMINATED BY ','
  LINES TERMINATED BY '\\n'
  FROM nodejs;";

 // uncomment next line if you want to see query string in browser
 //echo $qstring;

mysqli_query($con, $qstring);

mysqli_close($con);

?>

你可以填写你的用户和密码,db\u名称,把这个文件放在你的根文件夹中,然后在浏览器中测试它。

相关问题