i have a recursive table of category and a company table with fields like:
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
category tree is at max depth=3 ;
category cx -> category cy -> category cz
with knowledge of company categories are always linked to last category (c3), i want all categories that a company is linked to (c1z, c2z, c3z, c1y, c2y, c3y, c1x, c2x, c3x) for my search engine. //c1y is the parent of category_1 and c1x is parent of parent of category 1...
the best query i came up with is :
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
)
)
)
it has so much duplicate in it. one for category_* in company. and one for repeating it multiple times.
any way to remove all this duplicates ?
--update--
suppose we solve the category-* field with using two tables what about recursive problem with 3 levels of category?
for example if there is only one category it would look like
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
)
)
);