包含group_concat的mysql select语句

时间:2018-04-13 12:46:01

标签: mysql group-concat

我有一个像这样的mysql语句

SELECT distinct mk.gene as gene, qs.rs as snp, CONCAT (qs.A1, qs.A2) as genotype
FROM dallas.QS_base qs  cross join   
dallas.staging mk 
     ON qs.rs = mk.rs 
WHERE qs.sampleID = 'mydna' 
order by gene ASC;

返回此类型的输出

'ACE'    'RS4343',    'AA'
'ACTN3'  'RS1815739'  'TC'

来自这种类型的表(dallas.staging)

'heart health', 'ACE', 'RS4343'
'skin health', 'ACE', 'RS4343'
'sports performance', 'ACE', 'RS4343'
'sports performance', 'ACTN3', 'RS1815739'
'longevity', 'ACTN3', 'RS1815739'

和这个(dallas.QS_base)

'mydna','RS4343','A','A'
'mydna','RS1815739','T','C'

我应该如何更改上面的mysql语句以使我能够获得此输出?我相信我需要使用group_concat命令。

'ACE'    'RS4343',    'AA' '(heart health, sports performance, skin health)'
'ACTN3'  'RS1815739'  'TC' '(sports performance, longevity)'

1 个答案:

答案 0 :(得分:1)

这个查询应该为你完成这项工作(注意mk.gene上的不同是不必要的,因为你正在按它分组):

SELECT mk.gene as gene, qs.rs as snp, CONCAT (qs.A1, qs.A2) as genotype, GROUP_CONCAT(mk.condition) AS conditions
FROM QS_base qs  cross join   
staging mk 
     ON qs.rs = mk.rs 
WHERE qs.sampleID = 'mydna'
group by gene
order by gene ASC;

输出:

gene    snp         genotype    conditions
ACE     RS4343      AA          heart health,sports performance,skin health
ACTN3   RS1815739   TC          sports performance,longevity