Mike
Mike

Reputation: 1768

How to find grandchildren?

I'm trying to find all the grandchildren for a specific id, but I can't seem to get my joins correct. The below code works, but it I need to get the products associated with it from the products table.

SELECT b.category_id, b.category_name, b.parent, a.parent 
FROM categories AS a, categories AS b 
WHERE a.category_id = b.parent AND a.parent = 119

When I try to JOIN the products table I keep getting an error:

SELECT *
FROM products p
INNER JOIN products_categories pc
ON p.product_id = pc.product_id
INNER JOIN (
      SELECT b.category_id, b.category_name, b.parent, a.parent 
      FROM categories AS a, categories AS b 
      WHERE a.category_id = b.parent AND a.parent = 119
      )x

My desired result would be to have the following: (NOTE: Check out my SQL Fiddle to see the schema in code view)

(76, 'BR134', 'LEA530664', 'ITEM1234', 1499.99, 'yes', 'This is a nice gun'),
(77, 'mZCXGT', 'LEA471061', 'qwer345', 89.99, 'yes', 'Testing!'),
(78, 'ert', 'LEA023991', 'asdf34', 129.99, 'yes', 'Another test to get this right!'),
(79, 'model test', 'LEA355935', 'item test', 119.99, 'yes', 'This is another test dammit!'),
(80, 'CZV1354', 'LEA741837', 'LI-1234', 1299.99, 'yes', 'This is a hipoint weapon!'),
(81, 'PINK12G', 'LEA008558', 'PINK-SHG', 89.99, 'yes', 'YEP! This is pink!'),
(82, 'BOWTECH', 'LEA762521', 'asdf', 899.99, 'yes', 'This is a test!'),
(83, 'LX32', 'LEA346903', 'MADEUP', 1499.99, 'yes', 'This is Carters gun.');

SQL Fiddle:

http://sqlfiddle.com/#!2/dd66c/2

Here's my schema: enter image description here

Upvotes: 3

Views: 262

Answers (1)

pkmiec
pkmiec

Reputation: 2694

I think you are looking for this (I have added category names for "debuggability"):

SELECT 
  p.product_id
, p.model
, p.sku
, p.item_number
, p.msrp
, p.availability
, p.description
, grand_child.category_name AS grand_child_category
, child.category_name AS child_category
, parent.category_name AS parent_category
FROM categories parent
INNER JOIN categories child 
ON parent.category_id = child.parent 
INNER JOIN categories grand_child
ON child.category_id = grand_child.parent 
INNER JOIN products_categories pc
ON grand_child.category_id = pc.category_id 
INNER JOIN products p
ON p.product_id = pc.product_id
WHERE parent.category_id = 119

Upvotes: 2

Related Questions