mysql读取相同字段行,在MySQL中串联具有相同ID的行的字段

I have the following query:

SELECT mutations.id, genes.loc FROM mutations, genes where mutations.id=genes.id;

and outputs this:

| SL2.50ch02_51014904 | intergenic |

| SL2.50ch02_51014907 | upstream |

| SL2.50ch02_51014907 | downstream |

| SL2.50ch02_51014907 | intergenic |

| SL2.50ch02_51014911 | upstream |

| SL2.50ch02_51014911 | downstream |

My desired output is this:

| SL2.50ch02_51014904 | intergenic |

| SL2.50ch02_51014907 | upstream,downstream,intergenic |

| SL2.50ch02_51014911 | upstream,downstream |

I thought GROUP_CONCAT was useful for this. However, doing this:

SELECT mutations.id, GROUP_CONCAT(distinct(genes.loc)) FROM mutations, genes WHERE mutations.id=genes.id;

I have a unique row like this:

SL2.50ch02_51014904 | downstream,intergenic,upstream

How can I solve this?

解决方案

You need to add group by:

SELECT m.id, GROUP_CONCAT(distinct(g.loc))

FROM mutations m JOIN

genes g

ON m.id = g.id

GROUP BY m.id;

Along the way, you should learn a couple other things:

Use explicit join syntax. A simple rule: never use commas in the from clause.

Use table aliases (the m and g). They make the query easier to write and to read.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值