EDIT: A union is needed. The code below returns the right number of rows (which might be a fluke) but the if statements place "null" in the columns, so this is not useful. The correct way would be to make 3 select statements with a UNION to merge them into one query.
So I got the result I was looking for.
I hope this is useful to anyone else looking to get this kind of relationship:
table1.id in table2 and table3
table2.id in table 3
table4.id in table2 and table3
This basically allows someone to get results for something that can be categorized in more than one way, for example both products and product families can be categorized by manufacturer OR category.
The "if" statements narrow results so products not assigned to a family have family columns showing "null" and product families that do not have products have product columns showing "null". For example:
manufacturer1, family1, product1, cat1
manufacturer1, null, product2, cat2
manufacturer1, family2, null, cat2
where product1 belongs to family1, product 2 does not belong to a family and family2 has no specific product entries.
(note: the above lists results for manufacturer1
It can be easily modified to list results for category1)
Code:
SELECT
principals.ID as `company_id`
,principals.company_name as `company`
,if(products_family.ID = products.product_family_id
, products_family.ID, null) as `family_id`
,if(products_family.ID = products.product_family_id
, products_family.name,null) as `family_name`
,if(products_family.ID = products.product_family_id
, products.ID,null) as `product_id`
,if(products_family.ID = products.product_family_id
, products.product_family_id,null) as `product_family_id`
,if(products_family.ID = products.product_family_id
, products.name,null) as `product_name`
, products_categories.ID as `category_id`
, products_categories.cat_name as `category`
FROM principals, products_family, products, products_categories
WHERE principals.ID = 1
AND products_family.ID is not null
AND principals.ID = products_family.principal_id
AND products.product_family_id is not null
AND principals.ID = products.principal_id
AND (products_categories.ID = products.primary_cat_id
OR products_categories.ID = products_family.primary_cat_id)
ORDER BY `product_name`, `family_name`;
Bookmarks