mysql导出到csv并且相关字段已合并

时间:2012-03-31 16:58:47

标签: 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'

这只是一个基本的例子,但我希望这能传达我想要做的事情。

1 个答案:

答案 0 :(得分:2)

您可以将group_concat功能与SELECT ... 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

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