GROUP_CONCAT()内的条件

时间:2011-12-05 07:33:50

标签: mysql conditional-statements group-concat

伙计我的数据库中有以下表格

地点

  • id(主键)
  • 名称

项目

  • id(主键)
  • location_id(外键=>位置)
  • 项目名称

里程碑

  • id(主键)
  • 名称

状态

  • id(主键)
  • 状态

project_milestones

  • id(主键)
  • project_id(外键=>项目)
  • milestone_id(外键=>里程碑)
  • status_id(外键=>状态)

这里,为列出所有项目的所有里程碑(状态为9),我正在使用以下查询

SELECT projects.projectname, locations.name, DATE_FORMAT(projects.created_at, '%d-%m-%y') as     projectdate, 
 GROUP_CONCAT(milestones.name ORDER BY project_milestones.milestone_id ASC separator '<br/>')     AS milestones 
FROM projects INNER JOIN locations ON projects.location_id=locations.id 
INNER JOIN project_milestones ON project_milestones.project_id=projects.id  AND     project_milestones.status_id=9 
INNER JOIN milestones ON project_milestones.milestone_id=milestones.id 
INNER JOIN statuses ON project_milestones.status_id=statuses.id 
AND project_milestones.milestone_id=milestones.id GROUP BY  projects.projectname

结果如下所示

Location    Date Created    Project Name    Milestones (Status 9)
Bangalore   25-10-11        ABCD            CSO Contacts, Developer
Bangalore   11-11-11        Friday          Establish, Publish list
Bangalore   08-11-11        XX              CSO Contacts, Assemble,Layouts

它工作得很好,但我需要的是另一个GROUP_CONCAT专栏,用里程碑(状态10)来显示所有项目的所有里程碑(状态为10)。

输出与列出[Status-9里程碑]和[状态-10里程碑]的所有项目一样。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

SELECT  *,
        (
        SELECT  GROUP_CONCAT(m.name ORDER BY m.id)
        FROM    project_milestones pm
        JOIN    milestones m
        ON      m.id = pm.milestone_id
        WHERE   pm.project_id = p.id
                AND pm.status_id = 9
        ) milestone_9,
        (
        SELECT  GROUP_CONCAT(m.name ORDER BY m.id)
        FROM    project_milestones pm
        JOIN    milestones m
        ON      m.id = pm.milestone_id
        WHERE   pm.project_id = p.id
                AND pm.status_id = 10
        ) milestone_10
FROM    projects p
JOIN    locations l
ON      l.id = p.location_id