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,s.name FROM sub_category s LEFT JOIN category c ON c.category_id = s.category_id GROUP BY s.subcategory_id
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
, GROUP_CONCAT(
CONCAT( s.subcategory_id
, '|'
, s.name) ) AS subcategories
FROM category AS c
LEFT OUTER
JOIN sub_category AS s
ON s.category_id = c.category_id
GROUP
BY c.category_id
, c.category_name
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”