[英]mySQL - query to group values together
我有一个查询(下面),该查询返回ID值和两个附加的关联值(ReplacesReference)。 查询返回2条记录。 我想返回一条记录,因此需要将第一个“ ReplacesReference”值与逗号“,”和第二个“ ReplacesReference”值连接起来。
我的查询如下
select
distinct(c.wiid) as ID,
a.reference as ReplacesReference
from npp_projects a,
npp_assoc b,
npp_projects c
where a.id = b.parent_id
and b.type = 'replace'
and c.id = b.child_id
and c.reference like '%EN 815%'
输出为:
ID | ReplacesReference
====================================
CEN3406 | I.S. EN 815:1996
CEN3406 | I.S. EN 815:2004
我希望能够返回以下输出:
ID | ReplacesReference
====================================
CEN3406 | I.S. EN 815:1996 , I.S. EN 815:2004
在此先感谢您的帮助-我正在用这根头发撕掉!
您必须执行以下操作:
从表GROUP BY id中选择SELECT id,GROUP_CONCAT(string SEPARATOR''); http://dev.mysql.com/doc/refman/5.0/zh/group-by-functions.html#function_group-concat
您想使用group by
而不是select distinct
。 您在c.wild
周围使用括号表明您不了解select distinct
作品的方式。 它适用于select
列表中的所有列。 括号不影响它。 查询如下:
select p2.wiid as ID,
group_concat(distinct p.reference separator ', ') as ReplacesReference
from npp_projects p join
npp_assoc a
on p.id = a.parent_id
npp_projects p2
on p2.id = a.child_id
where a.type = 'replace' and p2.reference like '%EN 815%'
group by p2.wild;
我所做的更改:
group_concat()
以获取所需的列表。 group by
以替换select distinct
。 join
语法。 作为一个简单的规则:不要在from
子句中使用逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.