MySQL Group和Concat多列

时间:2023-02-14 04:18:03

I have to add two or more strings from MySQL database, for this I used CONCAT() function.

我必须从MySQL数据库中添加两个或更多字符串,为此我使用了CONCAT()函数。

Here is the first table classes which stores PHP classes.

这是第一个存储PHP类的表类。

class_id  class_name
--------  ----------
       1  accountant
       2  attendance

Another table methods which stores each class methods.

存储每个类方法的另一个表方法。

class_id  method_name            
--------  -----------------------
       1  __construct            
       1  add_expenses

       2  __construct            
       2  attendance_report

And I write the query for concatenation.

我写了连接查询。

SELECT 
  `cc`.`class_id`,
  `cc`.`class_name`,
  CONCAT(`cm`.`method_name`, ',') AS `method_name` 
FROM
  `classes` AS `cc` 
  LEFT JOIN `methods` AS `cm` 
    ON `cm`.`class_id` = `cc`.`class_id` 
GROUP BY `cc`.`class_name`;

Which is not working. My expected output is

哪个不行。我的预期产量是

class_id  class_name      method_name 
--------  --------------  ------------
       1  accountant      __construct, add_expenses, .... n
       2  attendance      __construct, attendance_report, .... n

Any ideas?

有任何想法吗?

1 个解决方案

#1


3  

Use

使用

GROUP_CONCAT

GROUP_CONCAT

instead of

代替

CONCAT

CONCAT

GROUP_CONCAT(cm.method_name) you do not needs to pass comma as separator that will be taken default.

GROUP_CONCAT(cm.method_name)您不需要将逗号作为默认值的分隔符传递。

#1


3  

Use

使用

GROUP_CONCAT

GROUP_CONCAT

instead of

代替

CONCAT

CONCAT

GROUP_CONCAT(cm.method_name) you do not needs to pass comma as separator that will be taken default.

GROUP_CONCAT(cm.method_name)您不需要将逗号作为默认值的分隔符传递。