Matthew Smart
Matthew Smart

Reputation: 1319

order group_concat values in one column

I have a database with 4 tables related to this question. I have only provided the required columns for each table to not get things complicated.





So a review can have multiple themes and multiple sub-themes. Each sub-theme should correspond to a theme, meaning a sub-theme cannot exist without its main theme.

The themes table is the place which holds the name for either the theme or sub-theme.

At the minute i have made a query which grabs all the data i require. Because it makes multiple rows i have done a group_concat for the themes and sub-themes. This means for each individual review i have a column called "themes". In this column it contains all the themes and sub-themes separated by a comma.

This is my query:

select `reviews`.`reviewID`,
   GROUP_CONCAT(`themes`.`name`) as `Name`
from `reviews`

left join `reviewthemes` on `reviewthemes`.`reviewId` =`reviews`.`reviewId`
left join `reviewsubthemes` on `reviewsubthemes`.`reviewid` = `reviews`.`reviewid`
left join `themes` on (`themes`.`themeid` = `reviewthemes`.`themeid` or `themes`.`themeid` = `reviewsubthemes`.`themeid`)

where `reviews`.`healthwatchID` = 32 
and (`review_created` BETWEEN '2015-08-01 00:00:00' AND '2015-08-31 23:59:59')
group by `reviews`.`reviewID`

This brings back data which looks like this:

enter image description here

Now here is the tricky part, and i'm not sure if i will need to do this in PHP or MYSQl but its safe to say i'm am really confused.

I require the format to be like :

theme - subtheme; theme - subtheme; theme;

So you can see i need a theme and a subtheme to have a semi colon at the end. But some reviews can have a theme with no sub-theme followed by a theme with a sub-theme.

What is the best way to go about this?

Upvotes: 0

Views: 41

Answers (1)

Kickstart
Kickstart

Reputation: 21513

You can use CONCAT to join the name and sub name together, and then GROUP_CONCAT on the results of that:-

select reviews.reviewID,
   GROUP_CONCAT(CONCAT_WS(' - ', t1.name, t2.name) SEPARATOR ';') as Name
from reviews

left join reviewthemes on reviewthemes.reviewId =reviews.reviewId
left join reviewsubthemes on reviewsubthemes.reviewid = reviews.reviewid
left join themes t1 on (t1.themeid = reviewthemes.themeid)
left join themes t2 on (t2.themeid = reviewsubthemes.themeid)
where reviews.healthwatchID = 32 
and (review_created BETWEEN '2015-08-01 00:00:00' AND '2015-08-31 23:59:59')
group by reviews.reviewID

Upvotes: 1

Related Questions