简体   繁体   English

MySQL-将值分组在一起的查询

[英]mySQL - query to group values together

I have a query (below) which returns and ID value and two additional associated values (ReplacesReference). 我有一个查询(下面),该查询返回ID值和两个附加的关联值(ReplacesReference)。 The query returns 2 records. 查询返回2条记录。 I want to return one record so I need to concatenate the first "ReplacesReference" value with a comma ',' and the second "ReplacesReference" value. 我想返回一条记录,因此需要将第一个“ ReplacesReference”值与逗号“,”和第二个“ ReplacesReference”值连接起来。

my query is as follows 我的查询如下

    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%'

Its output is : 输出为:

ID          |   ReplacesReference
====================================
CEN3406     |   I.S. EN 815:1996
CEN3406     |   I.S. EN 815:2004

I want to be able to return the below output: 我希望能够返回以下输出:

ID                | ReplacesReference
====================================
CEN3406           |  I.S. EN 815:1996 , I.S. EN 815:2004

Many thanks in advance for your help - I am tearing my hair out with this one ! 在此先感谢您的帮助-我正在用这根头发撕掉!

You'd have to do something like: 您必须执行以下操作:

SELECT id, GROUP_CONCAT(string SEPARATOR ' ') FROM table GROUP BY id; 从表GROUP BY id中选择SELECT id,GROUP_CONCAT(string SEPARATOR''); http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat http://dev.mysql.com/doc/refman/5.0/zh/group-by-functions.html#function_group-concat

You want to use group by instead of select distinct . 您想使用group by而不是select distinct Your use of parentheses around c.wild suggests that you don't understand how select distinct works. 您在c.wild周围使用括号表明您不了解select distinct作品的方式。 It applies to all columns in the select list. 它适用于select列表中的所有列。 The parentheses don't affect it. 括号不影响它。 The query looks like: 查询如下:

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;

The changes I made: 我所做的更改:

  • Added the group_concat() to get the list you want. 添加了group_concat()以获取所需的列表。
  • Added the group by to replace the select distinct . 添加了group by以替换select distinct
  • Changed the table aliases to use table abbreviations so the query is easier to follow. 更改了表别名以使用表缩写,因此查询更容易遵循。
  • Changed the join syntax to the more powerful explicit join syntax. 将联接语法更改为更强大的显式join语法。 As a simple rule: just do not use commas in the from clause. 作为一个简单的规则:不要在from子句中使用逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM