使用Group_concat

时间:2011-11-24 08:14:07

标签: mysql

我对此感到困惑,我想在使用GROUP_CONCAT时选择3表中的所有字段。我所做的就是这样,但它什么也没有回复。

SELECT
    personnel.Task_id AS personnel_Task_id,
    personnel.Top_id AS personnel_Top_id,
    GROUP_CONCAT(personnel.Personnel) AS Personnel,
    project.P_id AS project_P_id,
    project.P_name, project.P_manager, project.POC,
    project.TSD,
    project.TED,
    project.ASD AS project_ASD,
    project.AED AS project_AED,
    project.DT AS project_DT,
    project.DA AS project_DA,
    project.DV AS project_DV,
    task.Task_id AS task_Task_id,
    task.Top_id AS task_Top_id,
    task.Task_name,
    task.Frm,
    task.todate,
    task.ASD AS task_ASD,
    task.AED AS task_AED,
    task.P_id AS task_P_id,
    task.DT AS task_DT,
    task.DA AS task_DA,
    task.DV AS task_DV,
    task.Completion
FROM project_management.task,
     project_management.project,
     project_management.personnel
WHERE personnel.Task_id = task.Task_id
  AND project.P_id = task.P_id
  AND task.Top_id = '$oldID';

1 个答案:

答案 0 :(得分:1)

你需要使用GROUP BY进行群组连接让我给出解释

当您使用GROUP BY时,您需要使所有选择列兼容

这意味着您无法选择非分组列。

您需要在非分组列中使用组聚合函数

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

在此示例表中我们无法直接选择id

我们可以选择MAX(id)MIN(id)AVG(id)...

示例表

|-id -|-   Name    -|- Department -|
|- 1 -|-  Name 1   -|-     1      -|
|- 2 -|-  Name 2   -|-     1      -|
|- 3 -|-  Name 3   -|-     1      -|
|- 4 -|-  Name 4   -|-     2      -|

查询

SELECT GROUP_CONCAT(Name,DESC SEPARATOR ', ') As Names,Department
FROM person
GROUP BY Department

RESULT

|-id -|-          Names           -|- Department -|
|- 1 -|-  Name 1, Name 2, Name 3  -|-     1      -|
|- 2 -|-          Name 4          -|-     1      -|