【问题标题】:export mysql related tables to csv将mysql相关表导出到csv
【发布时间】:2015-02-02 05:56:47
【问题描述】:

我在数据库中有 3 个表,相关如下:

fruit_names ----> data <---- features

在与名称和特征表相关的数据中具有外键关系。因此,在单独的表中指定了一系列水果和一系列特征,数据表中给出了每种水果的每个特征的信息。也就是说,每个数据行只关联一个水果名称和一个特征名称;水果和特征的其他信息存储在另外两个表中。

我想要一个格式为表格的 csv,其特征为列,结果为行:

        roundness           enlongatedness          tastyness           difficulty_to_peel
apple   10 quite round      1 not enlongated        5 depends           2 very difficult
banana  1 not round at all  8 quite enlongated      10 always tasty     9 very easy
kiwi    8 little bit round  3 little bit enlongated 5 depends           7 easy
orange  10 quite round      1 not enlongated        6 most often tasty  7 easy

这个命令当然给了我相关信息,但格式不正确:

选择fruit_names_name、data_x、features_feature_name 从数据 加入功能 ON data.features_foreign = features.features_id 加入语言 ON data.fruit_names_foreign = fruit_names.fruit_names_id;

因为它在表格中显示数据如下:

fruit_names_name    data_x              features_feature_name
apple               10 quite round      roundness
apple               1 not enlongnated   enlongatedness
apple               3 depends           tastyness
apple               2 very difficult    difficulty_to_peel
banana              1 not round at all  roundness
banana              8 quite enlongated  enlongatedness
etc.

是否可以使用 phpmyadmin、php 脚本或 mysql 本身来生成可用的 .csv 文件?

【问题讨论】:

  • 是的,我意识到 SELECT INTO OUTFILE 是去这里的方式。但是如何将三个不同表格中的信息组合成所需的格式呢?我尝试将 SELECT INTO OUTFILE 与 UNION 结合使用,例如 SELECT data_x FROM data UNION SELECT features_feature_name FROM features UNION SELECT fruit_names_name FROM fruit_names INTO OUTFILE /Users/....;但这显然行不通。

标签: php mysql sql csv


【解决方案1】:

你可以像这样连接字段:-

SELECT CONCAT(fruit_names_name, ', ', data_x, ', ', ... etc)
FROM data 
JOIN features 
ON data.features_foreign = features.features_id 
JOIN languages 
ON data.fruit_names_foreign = fruit_names.fruit_names_id;

然后将输出复制到文本文件中

【讨论】:

  • 这仍然以列表格式输出数据,每个水果名称列出 X 次,然后是其特征,然后是特征名称,为数据中的每一行列出。这不是我想要的,请参阅问题。
  • 抱歉,我没有看到那部分。您可能需要 PIVOT 或 CROSSTAB - 也许此链接会有所帮助:en.wikibooks.org/wiki/MySQL/Pivot_table
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 2019-12-14
  • 2015-10-06
  • 2010-11-01
相关资源
最近更新 更多