Skip to content

Instantly share code, notes, and snippets.

@developerdino
Created April 18, 2016 23:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developerdino/8b90af4810b028a236f7652093f6fc83 to your computer and use it in GitHub Desktop.
Save developerdino/8b90af4810b028a236f7652093f6fc83 to your computer and use it in GitHub Desktop.
Get all parent records for a child category - is good for getting the records for a breadcrumb trail. Thanks to http://stackoverflow.com/questions/2441821/getting-all-parent-rows-in-one-sql-query
select t2.id, t2.name
from (
select
@r as _id,
(select @r := parent_id from categories where id = _id) as parent_id,
@l := @l + 1 as lvl
from
(select @r := :id, @l := 0) vars,
categories h
where @r <> 0) t1
join categories t2 on t1._id = t2.id
order by t1.lvl desc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment