简体   繁体   中英

Condition within GROUP_CONCAT()

Guys I have the following tables in my DB

locations

  • id (primary key)
  • name

projects

  • id (primary key)
  • location_id (foreign key => locations)
  • projectname

milestones

  • id (primary key)
  • name

statuses

  • id (primary key)
  • status

project_milestones

  • id (primary key)
  • project_id (foreign key => projects)
  • milestone_id (foreign key => milestones)
  • status_id (foreign key => statuses)

Here, For listing all the Milestones (which has status 9) of all projects, I'm using following query

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

Result looks like this

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

It's working great, But what I need is Another GROUP_CONCAT column say Milestones (Status 10) to display all the Milestones (which has status 10) of all projects.

Output like all Projects with [Status-9 Milestones] and [Status-10 milestones] listed. How can I do this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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