SELECT
sub_cat.id, sub_cat.name
FROM
sub_categories AS sub_cat
INNER JOIN product_table ON sub_cat.id = product_table.sub_category
GROUP BY
sub_cat.id, sub_cat.name
Try my example. An inner join will display results that exist on both tables. Therefore my example will show only subcategories that have a product of that type in the product table. The group by clause will remove duplicates that would be caused from having more than one product in a certain category.
Yes, I didn’t get a chance to test it so I definitely could have it wrong I’m much better at JOINs when I can actually test them against my data versus doing it blind.
All of these queries work for me (granted I ran them on SQL Server, but there isn’t any specific SQL Server syntax that wouldn’t work for MySQL too)
SELECT DISTINCT s.SubCategoryId, s.Name FROM #SubCategories AS s
RIGHT JOIN #Products AS p ON s.SubCategoryId = p.SubCategoryId
SELECT s.SubCategoryId, s.Name FROM #SubCategories AS s
RIGHT JOIN #Products AS p ON s.SubCategoryId = p.SubCategoryId
GROUP BY s.SubCategoryId, s.Name
SELECT s.SubCategoryId, s.Name FROM #SubCategories AS s
INNER JOIN #Products AS p ON s.SubCategoryId = p.SubCategoryId
GROUP BY s.SubCategoryId, s.Name
My Test Data (this is SQL Server specific)
CREATE TABLE #SubCategories
(
SubCategoryId INT,
Name VARCHAR(25)
)
INSERT INTO #SubCategories VALUES (1, 'Shoes')
INSERT INTO #SubCategories VALUES (2, 'Boxes')
INSERT INTO #SubCategories VALUES (3, 'Shirts')
INSERT INTO #SubCategories VALUES (4, 'Games')
CREATE TABLE #Products
(
ProductId INT,
SubCategoryId INT
)
INSERT INTO #Products VALUES (1, 1)
INSERT INTO #Products VALUES (2, 1) // create a second product with the same sub-category
// omit sub-category 2
INSERT INTO #Products VALUES (3, 3)
INSERT INTO #Products VALUES (4, 4)
Results
ID Name
----------------
1 Shoes
3 Shirts
4 Games
Edit:
@vinpkl ; your PHP code is incorrect, check your mysql_query statement, you have $result being passed into the function and you need to pass $qry
If I reversed the table order, it would have been fine though right? As that would prevent that issue… (granted if a sub_category had a null entry, it would return a null row).