D
D
Denis Popov2015-10-09 16:17:25
Database
Denis Popov, 2015-10-09 16:17:25

How to exclude children from a query?

Tell. I'm making a note program by category, I need to implement the movement of the category. As when forming a list of categories, where you can move to exclude the category itself, its descendants and descendants of descendants. If there are no problems with the first two, then there are problems with the last ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artur Polozov, 2015-10-09
@DenisDangerous

Clear.
1. Google tree building via JOIN (if the number of levels is limited)
2. SQLLite has CTE - recursion => standard tree building solution.
Build a tree from the desired node in the query by selecting their ID and then exclude them.

WHETE id NOT IN 
(
SELECT t2.id
FROM categories  AS t1
LEFT JOIN categories  AS t2 ON t2.parent_id = t1.id
WHERE t1.id = 1 ---- тут ваша категория переносимая
UNION 
SELECT t3.id
FROM categories  AS t1
LEFT JOIN categories  AS t2 ON t2.parent_id = t1.id
LEFT JOIN categories  AS t3 ON t3.parent_id = t2.id
WHERE t1.id = 1 ---- тут ваша категория переносимая
)

with recursion is more interesting:
WITH RECURSIVE CTE as (
  select 	Id, Name, parent_id, 0 as Level
  from categories
  where parent_id = @IdCategory  ---- тут ваша категория переносимая
  union all
  select 
  t2.Id, t2.Name, t2.parent_id, Level + 1
  from categories  t2
  join CTE on CTE.Id = t2.parent_id
 )
 SELECT * FROM categories
 WHERE Id NOT IN (SELECT Id FROM CTE )

I am not responsible for the syntax, there is no way to check)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question