iagdotme
iagdotme

Reputation: 993

Retrieve parent category name from table in MYSQL results

I have a MYSQL table called 'categories' from a project I inherited from someone else.

id         parent_id       name
1          NULL            Travel
2          NULL            Sleep
3          NULL            Eat
4          NULL            Bath
5          1               Prams
6          1               Travel Systems
7          2               Cots
8          3               High Chairs

The table is obviously a lot bigger than that, but you get the general idea. I have a MYSQL statement which brings together this table with other category, brand and product tables, but basically I want to list the parent category name from the above table with the sub-category in the statement. How do I do this?

My current statement is something like:

    SELECT brands.name, products.name,  categories.id, categories.name, brands.id, 
FROM `products` , `brands` , `categories`
WHERE products.brand_id = brands.id
AND products.category_id = categories.id
AND brands.name = '$brand'
ORDER BY categories.name, products.name

How do I retrieve the parent category names in the results? For example if the product is a Pram, how can I output "Travel". I could do seperate MYSQL statements in the loop but I want to avoid this. This is either a stupidly simple question (in which case I apologise for being brain dead) or a little more complicated! Thanks.

Upvotes: 0

Views: 2060

Answers (1)

Flupkear
Flupkear

Reputation: 2241

First you need to know the parent id of the current category and then get the name for that id, you could use a subquery in this way:

SELECT name FROM categories WHERE id = (SELECT pid FROM categories WHERE name = $brand)

EDIT: Since you need to get the category and subcategory names in the same row for a given subcategory id, try this:

SELECT sc.name AS subcategory, c.name AS category
FROM categories sc
LEFT JOIN categories c ON c.id = sc.parent
WHERE sc.id = $subcategory_id

Upvotes: 1

Related Questions