mysql - 连接Mysql中的字段

标签 mysql sql select string-concatenation

我有一张这样的 table

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

有什么办法可以做到这一点吗?

最佳答案

你可以使用group_concat

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

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

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

关于mysql - 连接Mysql中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30474663/

相关文章:

java - Spring、MySQL 和 Hibernate 返回针对列 'row_id' 调整的超出范围值

mysql - 使用索引优化带有 GROUP BY 子句的查询

mysql - 我需要删除列中所有前导 0

sql - 动态查询中 select 语句中的空格

mysql - 在巨大的 table 上加入 3 张 table 的速度非常慢

mysql - 如何通过phpmyadmin创建触发器?

php - ZF2 分页不适用于 Union

mysql - 统一这 2 个使用 3 个表的查询

javascript - 显示/隐藏基于关闭输入数字范围的选择 jQuery

php - 在MYSQL中选择未注册的值