我需要对此数据库进行快速递归sql查询:
SITE CATEGORY DIR PARENT_CATEGORY
domain1.com home home
domain1.com kitchen kitchen home
domain1.com appliances apps home
domain1.com tables tables kitchen
domain2.com home home-dir
domain2.com bathroom bath
domain2.com garden garden
domain3.com fun funny
我需要的是一个函数,它将为我提供从当前到顶级类别的父类别数组。例如,对于domain1.com表,它应该返回:
$breadcrumb = Array(
[0]=>Array(
'title'='home',
'dir'='home'
);
[1]=>Array(
'title'='kitchen',
'dir'='kitchen'
);
[2]=>Array(
'title'='tables',
'dir'='tables'
);
);
所以基本上,它应该返回所请求类别&的痕迹现场。 功能($ category,$ site){...
返回数组。 }
答案 0 :(得分:0)
查询有效,将为您提供最多7级的层次结构深度以及单行中的所有父级。 有点像:
SITE CATEGORY level1 level2 level3 level4 level5 -------------------------------------------------------------------------------- domain1.com tables tables kitchen home NULL NULL
select level1, level2, site, category, dir, parent_category
if(level7 is not null,7,
if(level6 is not null and level7 is null,6,
if(level5 is not null and level6 is null,5,
if(level4 is not null and level5 is null,4,
if(level3 is not null and level4 is null,3,
if(level2 is not null and level3 is null,2,1)))))) depth
from
(select
site,category,dir,parent_category
site level1,
parent_category level2,
(select parent_category from <table> i where one.parent_category=i.category) level3,
(select parent_category from <table> i where level3=i.category) level4,
(select parent_category from <table> i where level4=i.category) level5,
(select parent_category from <table> i where level5=i.category) level6,
(select parent_category from <table> i where level6=i.category) level7
from
<table> one
WHERE one.site = ?
)a;
注意:你可能需要做一些调整