In my osCommerce store I want to fetch the parent_id of categories that either have no sub category or child categories.
I used the following in my code:
$categories_query = tep_db_query("select c.categories_id, cd.categories_name
from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd
where c.parent_id = '$parent_id' and
c.categories_id = cd.categories_id
order by sort_order, cd.categories_name");
The above translates into this when the constants are filled in:
select c.categories_id, cd.categories_name
from categories c, categories_description cd
where c.parent_id = '$parent_id' and
c.categories_id = cd.categories_id
order by sort_order, cd.categories_name
2
Answers
Without knowing your table layouts, there’s some guessing needed to answer your question. But, I believe you need a query like this:
Note that this
LEFT JOIN ... WHERE ... IS NULL
pattern matches the rows in the first table joined that don’t have a match in the second table.You can go with this:
or you can go with that:
But what you really want to know about is this line:
Since the
parent_id
column is in the same table as the one you’re looking up and not in another you’ll need to look up the table on itself and reference it via another alias.This part of the SQL will return all the
categories_id
(actuallyparents_id
in the table) that are being referenced as parent categories:Now, when you put that into a
NOT IN
comparison you’re left with rows that do not have any children categories underneath.