简体   繁体   English

在 mysql 中在一列中合并多行? 当具有不同值的相同 ID 时

[英]In mysql combine multiple rows in one column? when having same ID with different value

i have a query in which getting 2 record of same id but different groups(column) value.我有一个查询,其中获取 2 条相同 id 但不同组(列)值的记录。 here is the query:这是查询:

SELECT rule.id, rule.rule_name,group_rule.groupName
  FROM rule LEFT JOIN rule_groups ON rule.id=rule_groups.rule_id
  LEFT JOIN group_rule ON   rule_groups.group_rule_id=group_rule.id

result: ---------------------------------结果: - - - - - - - - - - - - - - - - -

|id     |rule_name   | groupName
|1      |A           | app
|1      |A           |jaz

now want to combine these two rows in one record.现在想将这两行合并到一条记录中。 how to modify query to get expected result.如何修改查询以获得预期结果。

expected:预期的:

|id     |rule_name   | groupName
|1      |A           | app, jaz




 

I think you just want group_concat() :我想你只想要group_concat()

select r.id, r.rule_name, group_concat(gr.groupName separator ', ')
from rule r left join
     rule_groups rg
     on r.id = rg.rule_id left join
     group_rule gr
     on rg.group_rule_id = gr.id
group by r.id, r.rule_name;

Note that I also introduced table aliases so the query is easier to write and read.请注意,我还引入了表别名,因此查询更易于编写和阅读。

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

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