【问题标题】:Concatenate fields in Mysql连接Mysql中的字段
【发布时间】:2015-05-27 06:24:32
【问题描述】:

我有一张这样的桌子

id   name   value
1    Ram     a
2    John    b
3    Ram     c
4    Ram     d
5    John    e

我想要这样的输出

name   value
Ram     a,c,d
John    b,e

有没有办法执行这个查询?

更新:

表格格式:

id   field1   value  field2
1    val1     a       null
2    val2     b       null
3    val1     c       null
4    val2     d       null
5    null     e       val1
5    null     f       val1
5    null     g       val2
5    null     h       val2

输出:

field1   field2   value
val1      null    a,c
val2      null    b,d
null      val1    e,f
null      val2    g,h

有什么办法可以做到吗?

【问题讨论】:

    标签: mysql sql select string-concatenation


    【解决方案1】:

    您可以使用group_concat

    select
    name, group_concat(value separator ',') as value
    from table_name
    group by name
    

    此外,如果您希望对值进行排序,您可以在 group concat 中使用 order by as

    select
    name, group_concat(value order by value) as value
    from table_name
    group by name
    

    【讨论】:

    • 也不要更改原始问题,第一个答案对于提供的问题非常正确。
    • 这不回答修改后的问题。
    • @TimBiegeleisen 检查我评论中的小提琴链接,它几乎可以回答修改后的问题。 :)
    【解决方案2】:

    使用group_concat()

    SELECT name, GROUP_CONCAT(value) AS value FROM my_table group by name
    

    【讨论】:

    • 尝试按 field1,field2 分组
    【解决方案3】:

    group_concat 函数应该可以为您解决问题:

    SELECT   name, GROUP_CONCAT(value) AS value
    FROM     my_table
    GROUP BY name
    

    【讨论】:

      【解决方案4】:

      Mysql GROUP_CONCAT 可以帮助你。请参阅此链接中的示例https://www.percona.com/blog/2013/10/22/the-power-of-mysqls-group_concat/

      【讨论】:

        【解决方案5】:

        你必须使用group_concat

        select name,group_concat(value) from tablename group by name
        

        【讨论】:

          【解决方案6】:

          使用这个:

          SELECT field1, field2, GROUP_CONCAT(value ORDER BY value SEPARATOR ',')
          AS value FROM table
          GROUP BY field1, field2;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-01-05
            • 2012-08-07
            • 2011-01-21
            • 2018-12-07
            • 1970-01-01
            • 2013-10-26
            • 1970-01-01
            • 2016-12-07
            相关资源
            最近更新 更多