How to fix this using GROUP_CONCAT() fun in mysql

Hi there I working on an e-commerce project and want to fetch all sub categories along with their parent categories
this is my SQL query

SELECT c.category_id cat_id,c.category_name cat_name,s.subcategory_id, FROM sub_category s LEFT JOIN category c ON c.category_id = s.category_id GROUP BY s.subcategory_id

And here is the output:

I want to remove duplicates by using GROUP CONCAT

okay, i know what you mean even though there aren’t any duplicates ;o)

first of all, let’s start with this –

FROM sub_category s LEFT JOIN category c 

this LEFT JOIN is structured so that it will return all subcategories even if they don’t have a parent category

i’m pretty sure you want this –

FROM category c LEFT JOIN sub_category s

this LEFT JOIN is structured so that it will return all categories even if they don’t have any child subcategories

and now what you want is easier… you want one result row per category, with subcategories handled by GROUP_CONCAT

SELECT c.category_id    AS cat_id
     , c.category_name  AS cat_name
             CONCAT( s.subcategory_id
                   , '|'
                   , ) AS subcategories
  FROM category AS c
  JOIN sub_category AS s  
    ON s.category_id = c.category_id 
    BY c.category_id    
     , c.category_name 
1 Like

Yes Exactly this is what I want!

@r937 Thanks you Bro

One more thing I want to ask you is that “I am very bad in SQL queries I am recently pass out my highschool all thing about web programming I know due Self learning from youtube,udemy and these kind of platform and more peoples like you So, if it’s possible could you please recommend me a SQL Book so I can improve my SQL knowledge”

yes, i sure can

“Simply SQL” available from

i am not sure about the various ways to purchase it, and i think you can even find it on Amazon and other sites

but that’s the book i would recommend… absolutely first class stuff


1 Like

Not that you’re biased or anything :winky:

(It is a good book, though…)

1 Like

Thank alot one more time :innocent: InshahAllah I read this book :+1:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.