I currently have this sql statement that I wrote and it works but it’s not quite what I want. I’ve been working on it for hours but can’t seem to get any further.
select parent.id as parent_id, parent.subject as parent,s.id,s.subject from (select s.id, s.subject from subjects s where parent_id = 0) parent join subjects s on parent.id = s.parent_id order by parent.subject, s.subject
It’s grabbing all the subjects and ordering correctly but I also want to return the parent subject (parent_id = 0) at the top of each grouping. This is because some parents may not have subjects underneath but I still need to return them. Also the ordering is off when I try to do it as I want the parent first then it’s child subjects. Hope that makes sense but if not just ask.
Any help would be appreciated.
Thanks
Steve
You’re talking about grouping sets of rows by their parent rows.
The only way I know how to do this in MySQL is using the
GROUP_CONCAT()function which won’t group the subjects by row, but rather create a grouped string.Here’s what you can do:
So this will give you a result set like:
Depending on what language you are using in your application, you may be able to “explode” the
subjectsstring into arrays delimited first by|||which separates each subject, then:::which separates that subject’s ID and name.Obviously, the downside of this is you have to make sure that your child subject name does not contain either
|||or:::or whichever delimiters you decide to use.Edit: Experimentally, I came up with this alternative solution which may be closer to what you’re looking for:
Try:
This query should give you a result along the lines of: