我有一个类别的递归表和一个包含以下字段的公司表:
category(id, name, parent) // parent is foreign key to category id :)
company(id, category_1, category_2, category_3) // category_* is foreign key to category id
类别树的最大深度=3;
类别 cx -> 类别 cy -> 类别 cz
知道公司类别总是链接到最后一个类别(c3),我想要一个公司链接到的所有类别(c1z,c2z,c3z,c1y,c2y,c3y,c1x,c2x,c3x)用于我的搜索引擎。//c1y是category_1的父类,c1x是category_1的父类...
我想出的最好的查询是:
SELECT
ID,
NAME
FROM category c3
WHERE ID IN (
select category_1 from company where id=:companyId
union
select category_2 from company where id=:companyId
union
select category_3 from company where id=:companyId
union
select parent from category where id in (
select category_1 from company where id=:companyId
union
select category_2 from company where id=:companyId
union
select category_3 from company where id=:companyId
)
union
select parent from category where id in (
select parent from category where id in (
select category_1 from company where id=:companyId
union
select category_2 from company where id=:companyId
union
select category_3 from company where id=:companyId
)
)
)
它有很多重复。一个用于公司中的 category_*。一个用于重复多次。
有什么方法可以删除所有这些重复项?
- 更新 -
假设我们使用两个表来解决 category-* 字段,那么具有 3 级类别的递归问题呢?
例如,如果只有一个类别,它看起来像
SELECT
ID,
NAME
FROM category
WHERE ID IN (
select category_1 from company where id=:companyId
union
select parent from category where id in (
select category_1 from company where id=:companyId
)
union
select parent from category where id in (
select parent from category where id in (
select category_1 from company where id=:companyId
)
)
);