【问题标题】:mysql export to csv with related fields concatedmysql 导出到 csv 并连接相关字段
【发布时间】:2012-03-31 16:58:46
【问题描述】:

我需要将我的 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')

我怎么会得到这个:

'一些名字','ident1 ident2','蓝绿色'

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

【问题讨论】:

  • 为什么没有 2 行:一个用于ident1,另一个用于ident2
  • 因为这会造成大量不必要的重复。我最终可能只有 1 个项目有 20 条记录。

标签: mysql export-to-csv


【解决方案1】:

您可以将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

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

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

【讨论】:

    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2016-08-24
    • 2018-12-07
    • 2012-05-21
    • 2011-04-25
    相关资源
    最近更新 更多