tags:

views:

377

answers:

1

I have three tables: categories, subcategories and subsubcategories.

I want to display a list that's formatted like:

dvds
cds
cds > pop
cds > blues
cds > new age
cds > new age > whale noises
books
books > cowboys
books > zombies

I've managed to display everything except for the names of categories on their own when they have children, eg what I'm getting is:

dvds
cds > pop
cds > blues
cds > new age > whale noises
books > cowboys
books > zombies

The above list is missing the cds and books categories, plus the cds > new age subcategory.

The query I'm using is:

SELECT
  c.name AS c_name,
  sc.name AS sc_name,
  ssc.name AS ssc_name
FROM
  categories c
LEFT JOIN
  subcategories sc
  ON c.id = sc.category_id
LEFT JOIN
  subsubcategories ssc
  ON sc.id = ssc.subcategory_id

Any help with this would be much appreciated!

A: 
SELECT  *
FROM    (
        SELECT  DISTINCT
                c.name AS c_name,
                sc.name AS sc_name,
                ssc.name AS ssc_name
        FROM    categories c
        LEFT JOIN
                subcategories sc
        ON      c.id = sc.category_id
        LEFT JOIN
                subsubcategories ssc
        ON      sc.id = ssc.subcategory_id
        GROUP BY
                c.name, sc.name, ssc.name WITH ROLLUP
        HAVING  c_name IS NOT NULL
        ) q
ORDER BY
        c_name, sc_name, ssc_name
Quassnoi
Thanks for the quick response. That's almost right except it's displaying category_name twice for categories with no children. Categories with subcategories and subsubcategories are working prefectly though.
Dan
Oh wait, no they're not working perfectly. They're displaying as cds > whale noises and cds > new age > whale noises, instead of cds > new age and cds > new age > whale noises.
Dan
@Dan: try now .
Quassnoi
Dan
@Dan: just checked on your very data, got `cds > new age`, `cds > new age > whale noises`. Could you please post the dump of your tables here?
Quassnoi
Oh sorry, you're completely right. I'd missed out the ssc.name in the group by, it's working absolutely perfectly now. Thanks for all your help :)
Dan