mysql 导出到 csv 并连接相关字段

标签 mysql export-to-csv

我需要将我的 mysql 数据库导出到一个 csv 文件。我要使用它的地方不能有相关表,所以我需要将相关记录连接到一个字段中。这可能吗?例如,假设这个表结构:

Items: id as INT, name as VARCHAR
ItemIdentifiers: id as INT, item_id as INT, identifier_id as INT
Identifiers: id as INT, identifier as VARCHAR
ItemColors: id as INT, item_id as INT, color_id as INT
Colors: id as INT, color as VARCHAR

并假设此数据:

Items: (1, 'some name')
ItemIdentifiers: (1, 1, 1), (2, 1, 2)
Identifiers: (1, 'ident1'), (2, 'ident2')
ItemColors: (1, 1, 1), (2, 1, 2)
Colors: (1, 'blue'), (2, 'green')

我怎样才能得到这个:

'some name', 'ident1 ident2', 'blue green'

这只是一个基本示例,但我希望它能传达我正在尝试做的事情。

最佳答案

您可以使用 group_concatSELECT ... INTO结合使用的功能

SELECT DISTINCT
       items.name AS `Name`, 
       GROUP_CONCAT(DISTINCT identifiers.identifier 
               ORDER BY identifiers.identifier 
               SEPARATOR ' ') AS `Identifiers`, 
       GROUP_CONCAT(DISTINCT colors.color 
               ORDER BY colors.color 
               SEPARATOR ' ') AS `colors` 
       INTO OUTFILE '/tmp/data.csv'
       FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
       LINES TERMINATED BY '\n'
FROM   items 
       JOIN itemidentifiers 
         ON ( itemidentifiers.item_id = items.id ) 
       JOIN identifiers 
         ON ( itemidentifiers.identifiers_id = identifiers.id ) 
       JOIN itemcolors 
         ON ( itemcolors.item_id = items.id ) 
       JOIN colors 
         ON ( colors.id = itemcolors.color_id ) 
GROUP BY Items.id

您可能会注意到有太多的JOIN。这是因为你使用了关系表。对于每个关系表,都有 1 个额外的 JOIN

注意:以上查询是实验性的。我还没有测试过。

关于mysql 导出到 csv 并连接相关字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957870/

相关文章:

python - 使用复杂的列表数据编写 CSV 文件

c# - C#中Append CSV函数的自动增量值

ruby-on-rails-3 - Rails 将搜索结果持久化到 CSV 输出

csv - 将 yajra 数据表的所有数据导出到 csv

c# - 以CSV格式导出到EXCEL时用逗号(,)分隔字符串c#

java - 连接远程数据库时出现 JDBC 错误

php - 没有显示 mysql select all 的结果

php - 两阶段 in_array 检查存在问题,不允许处理第二条语句

mysql - 在日期字段中保留加入时更新速度问题

mysql - 如何减去行中的两个日期(查询中未给出)Mysql