SELECT i.*,
parent.name AS 'Parent',
child.name AS 'Child'
FROM items i
LEFT JOIN categories child ON i.category_id = child.category_id
LEFT JOIN categories parent ON child.parent = parent.category_id
WHERE i.name = "Pepsi";
I am getting Parent = NULL, while Child equals the name of the Parent. Is there something wrong in my order of LEFT JOINs ?
So I will assume your table still has Pepsi in the category Pepsi, which has no parent.
LEFT JOIN categories child ON i.category_id = child.category_id
So, “Pepsi”'s category id matches the category ID for “Pepsi”. (Naming your item and your category the same is going to make this confusing.)
LEFT JOIN categories parent ON child.parent = parent.category_id
The Pepsi category’s parent field is NULL. so this doesnt join anything; or rather, it joins no data to the new columns.