SQL query to get full path from node - sql

I have a tree structure table, and I need to find the full path of an element, but in the same time, the elements are restricted by permissions
I have one table tblMapping
map_id name parent_id
1 Root 0
2 Child 1 1
3 Child 2 1
4 Child 3 3
5 Child 4 4
6 Child 5 5
And a tblPerms table:
perm_id map_id
1 5
2 6
I am using the following CTE query:
;WITH Hierarchy (map_id, name, parent_id, Path)
AS
(
SELECT
t.map_id, t.name, t.parent_id,
CAST(t.name AS varchar(max))
FROM
tblMapping t
LEFT OUTER JOIN
tblMapping t1 ON t1.map_id = t.parent_id
LEFT OUTER JOIN
tblPerms t2 ON t2.map_id = t1.map_id
WHERE
t1.map_id IS NULL
UNION ALL
SELECT
t.map_id, t.name,t.parent_id,
CAST(h.Path + '.' + t.name AS varchar(max))
FROM
Hierarchy h
INNER JOIN
tblMapping t ON t.parent_id = h.map_id
)
SELECT Path
FROM Hierarchy
WHERE Path is not null
OPTION (MAXRECURSION 0)
That CTE query will give me the path similiar to Child 4.Child 5
What I would like to have is to be able to have the full path of elements, even if permission is not set for: Root.Child 1.Child 3.Child 4.Child 5
Any idea on how to solve this request?
Thank you!

First build paths then check permissions
WITH Hierarchy (map_id, name, parent_id, Path)
AS
(
SELECT
t.map_id, t.name, t.parent_id,
CAST(t.name AS varchar(max))
FROM
tblMapping t
LEFT OUTER JOIN
tblMapping t1 ON t1.map_id = t.parent_id
WHERE
t1.map_id IS NULL
UNION ALL
SELECT
t.map_id, t.name,t.parent_id,
CAST(h.Path + '.' + t.name AS varchar(max))
FROM
Hierarchy h
INNER JOIN
tblMapping t ON t.parent_id = h.map_id
)
SELECT Path
FROM Hierarchy h
JOIN tblPerms t2 ON t2.map_id = h.map_id
WHERE Path is not null
OPTION (MAXRECURSION 0);

Related

SQL Get lowest level child and root node

I have database schema: [Id], [ParrentId], [some more tables]
I have hierarchy like:
1. a
2. aa
3. aaa_1
3. aaa_2
1. b
2. bb
1. c
2. cc
3. ccc_1
4. cccc
3. ccc_2
I want a (select * where X) => [X, lowest leve child] like:
[a, aaa_1] [a, aaa_2]; [cc, cccc] etc.
I can get lowest child with
SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;
but I don't know how to join it with root node.
Given:
The DBMS is SQL Server;
The highest level nodes of the tree have parent = NULL;
You want all the lowest leaves for all levels of the trees, not just the roots;
You want to have all the nodes at a lowest level, not just one;
This query would do it:
WITH r ( category_id, name, root, depth )
-- finds the root relationship
AS (
SELECT category_id, name, category_id, 0
FROM category
-- WHERE parent IS NULL -- this would only look at root nodes
UNION ALL
SELECT c.category_id, c.name, r.root, r.depth + 1
FROM r
JOIN category c
ON c.parent = r.category_id
), s ( category_id, name, root, window_id )
-- finds the lowest leaves
AS (
SELECT category_id, name, root, RANK() OVER(partition by root order by depth DESC)
FROM r
)
SELECT c.name AS NodeName, s.Name AS DeepLeafName
FROM category c
JOIN s
ON c.category_id = s.root
WHERE s.window_id = 1;
Here is the result set:
With SQL Server, you can try this :
With CTE as
(
Select ID as Child, lev = 1
from category
where ID = X
UNION ALL
Select category.ID, CTE.lev + 1
from category
inner join CTE ON category.ParentID = CTE.Child
)
select CTE_1.Child, CTE_2.Child
from CTE as CTE_1
inner join CTE as CTE_2
where CTE_1.lev = 1 AND CTE_2.lev = (select MAX(CTE.lev) from CTE)

get last node given the full path of all ancestor's node attributes using cte

Given the following PostgreSQL table:
items
integer id
integer parent_id
string name
unique key on [parent_id, name]
parent_id is null for all root nodes
Currently I build the sql query manually, doing a join for every path element. But is seems quite ugly to me and of course it limits the possible depth.
Example:
path: holiday,images,spain
SELECT i3.*
FROM items AS i1
, items AS i2
, items AS i3
WHERE i1.parent_id IS NULL AND i1.name = 'holiday'
AND i2.parent_id=i1.id AND i2.name = 'images'
AND i3.parent_id=i2.id AND i3.name = 'spain'
I wonder if there's a better way, probably using CTE?
You can see how my current code works and what the expected output is here:
http://sqlfiddle.com/#!1/4537c/2
update2 here's a function, it peforms well, because search goes only within the path, starting from parent:
create or replace function get_item(path text[])
returns items
as
$$
with recursive cte as (
select i.id, i.name, i.parent_id, 1 as level
from items as i
where i.parent_id is null and i.name = $1[1]
union all
select i.id, i.name, i.parent_id, c.level + 1
from items as i
inner join cte as c on c.id = i.parent_id
where i.name = $1[level + 1]
)
select c.id, c.parent_id, c.name
from cte as c
where c.level = array_length($1, 1)
$$
language sql;
sql fiddle demo
update I think you can do recursive traversal. I've written sql version of this, so it's a bit messy because of cte, but it's possible to write a function:
with recursive cte_path as (
select array['holiday', 'spain', '2013'] as arr
), cte as (
select i.id, i.name, i.parent_id, 1 as level
from items as i
cross join cte_path as p
where i.parent_id is null and name = p.arr[1]
union all
select i.id, i.name, i.parent_id, c.level + 1
from items as i
inner join cte as c on c.id = i.parent_id
cross join cte_path as p
where i.name = p.arr[level + 1]
)
select c.*
from cte as c
cross join cte_path as p
where level = array_length(p.arr, 1)
sql fiddle demo
or you can build path for all of the elements using recursive cte for that and accumuate your path into array or string:
with recursive cte as (
select i.id, i.name, i.parent_id, i.name::text as path
from items as i
where i.parent_id is null
union all
select i.id, i.name, i.parent_id, c.path || '->' || i.name::text as path
from items as i
inner join cte as c on c.id = i.parent_id
)
select *
from cte
where path = 'holiday->spain->2013';
or
with recursive cte as (
select i.id, i.name, i.parent_id, array[i.name::text] as path
from items as i
where i.parent_id is null
union all
select i.id, i.name, i.parent_id, c.path || array[i.name::text] as path
from items as i
inner join cte as c on c.id = i.parent_id
)
select *
from cte
where path = array['holiday', 'spain', '2013']
sql fiddle demo
This should perform very well, as it eliminates impossible paths immediately:
WITH RECURSIVE cte AS (
SELECT id, parent_id, name
,'{holiday,spain,2013}'::text[] AS path -- provide path as array here
,2 AS lvl -- next level
FROM items
WHERE parent_id IS NULL
AND name = 'holiday' -- being path[1]
UNION ALL
SELECT i.id, i.parent_id, i.name
,cte.path, cte.lvl + 1
FROM cte
JOIN items i ON i.parent_id = cte.id AND i.name = path[lvl]
)
SELECT id, parent_id, name
FROM cte
ORDER BY lvl DESC
LIMIT 1;
Assuming you provide a unique path (only 1 result).
->SQLfiddle demo
Too late to post my answer (very equivalent to Roman's and Erwin's) But an improvement on the table definition instead:
CREATE TABLE items
( id integer NOT NULL PRIMARY KEY
, parent_id integer REFERENCES items(id)
, name varchar
, UNIQUE (parent_id,name) -- I don't actually like this one
); -- ; UNIQUE on a NULLable column ...
INSERT INTO items (id, parent_id, name) values
(1, null, 'holiday')
, (2, 1, 'spain'), (3, 2, '2013')
, (4, 1, 'usa'), (5, 4, '2013')
;

Finding Top level parent of each row of a table [SQL Server 2008]

I have following two tables
Table Person
Id Name
1 A
2 B
3 C
4 D
5 E
Table RelationHierarchy
ParentId CHildId
2 1
3 2
4 3
This will form a tree like structure
D
|
C
|
B
|
A
ParentId and ChildId are foreign keys of Id column of Person Table
I need to write SQL that Can fetch me Top Level Parent i-e Root of Each Person.
Following CTE can do this for Each. I converted that to a Function and ran it for each row of Person. I have got about 3k rows in Person table and it takes about 10 Secs to do that. Can anyone suggest a approach that can take less. The Problem is the function that runs following CTE runs 3k times
DECLARE #childID INT
SET #childID = 1 --chield to search
;WITH RCTE AS
(
SELECT *, 1 AS Lvl FROM RelationHierarchy
WHERE ChildID = #childID
UNION ALL
SELECT rh.*, Lvl+1 AS Lvl FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.CHildId = rc.ParentId
)
SELECT TOP 1 id, Name
FROM RCTE r
inner JOIN dbo.Person p ON p.id = r.ParentId
ORDER BY lvl DESC
I have also updated the answer in the original question, but never-mind, here is a copy also:
;WITH RCTE AS
(
SELECT ParentId, ChildId, 1 AS Lvl FROM RelationHierarchy
UNION ALL
SELECT rh.ParentId, rc.ChildId, Lvl+1 AS Lvl
FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.ChildId = rc.ParentId
)
,CTE_RN AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY r.ChildID ORDER BY r.Lvl DESC) RN
FROM RCTE r
)
SELECT pc.Id AS ChildID, pc.Name AS ChildName, r.ParentId, pp.Name AS ParentName
FROM dbo.Person pc
LEFT JOIN CTE_RN r ON pc.id = r.CHildId AND RN =1
LEFT JOIN dbo.Person pp ON pp.id = r.ParentId
SQLFiddle DEMO
Note that the slight difference is in recursive part of CTE. ChildID is now rewritten each time from the anchor part. Also addition is ROW_NUMBER() function (and new CTE) to get the top level for each child at the end.
EDIT - Version2
After finding a performance issues with first query, here is an improved version. Going from top-to-bottom, instead of other way around - eliminating creating of extra rows in CTE, should be much faster on high number of recursions:
;WITH RCTE AS
(
SELECT ParentId, CHildId, 1 AS Lvl FROM RelationHierarchy r1
WHERE NOT EXISTS (SELECT * FROM RelationHierarchy r2 WHERE r2.CHildId = r1.ParentId)
UNION ALL
SELECT rc.ParentId, rh.CHildId, Lvl+1 AS Lvl
FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rc.CHildId = rh.ParentId
)
SELECT pc.Id AS ChildID, pc.Name AS ChildName, r.ParentId, pp.Name AS ParentName
FROM dbo.Person pc
LEFT JOIN RCTE r ON pc.id = r.CHildId
LEFT JOIN dbo.Person pp ON pp.id = r.ParentId
SQLFiddle DEMO
You could try to use a loop. As you will get many levels of recursion with your approach:
declare #child int = 0
declare #parent int = 1 --child to search
while #child <> #parent
BEGIN
set #child = #parent
select #parent = Parentid from #parentchild where ChildID = #child
END
select #parent
Another way to do this in a loop if you wanted to work with sets is:
SELECT *
INTO #parentchild
from RelationHierarchy
WHILE EXISTS
(select 1 from #parentchild A inner join #parentchild B on A.ChildID = B.ParentID Where A.ParentID <> B.ParentID )
BEGIN
update B set B.ParentID = A.ParentID
from #parentchild A inner join #parentchild B on A.ChildID = B.ParentID
END
select * from #parentchild

Finding a Top Level Parent in SQL

I have got two tables as following
Table Person
Id Name
1 A
2 B
3 C
4 D
5 E
Table RelationHierarchy
ParentId ChildId
2 1
3 2
4 3
This will form a tree like structure
D
|
C
|
B
|
A
ParentId and ChildId are foreign keys of Id column of Person Table
I need to write SQL that Can fetch me Top Level Parent i-e Root. Can anyone suggest any SQL that can help me accomplish this
You can use recursive CTE to achieve that:
DECLARE #childID INT
SET #childID = 1 --chield to search
;WITH RCTE AS
(
SELECT *, 1 AS Lvl FROM RelationHierarchy
WHERE ChildID = #childID
UNION ALL
SELECT rh.*, Lvl+1 AS Lvl FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.CHildId = rc.ParentId
)
SELECT TOP 1 id, Name
FROM RCTE r
inner JOIN dbo.Person p ON p.id = r.ParentId
ORDER BY lvl DESC
SQLFiddle DEMO
EDIT - for updated request for top level parents for all children:
;WITH RCTE AS
(
SELECT ParentId, ChildId, 1 AS Lvl FROM RelationHierarchy
UNION ALL
SELECT rh.ParentId, rc.ChildId, Lvl+1 AS Lvl
FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.ChildId = rc.ParentId
)
,CTE_RN AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY r.ChildID ORDER BY r.Lvl DESC) RN
FROM RCTE r
)
SELECT r.ChildId, pc.Name AS ChildName, r.ParentId, pp.Name AS ParentName
FROM CTE_RN r
INNER JOIN dbo.Person pp ON pp.id = r.ParentId
INNER JOIN dbo.Person pc ON pc.id = r.ChildId
WHERE RN =1
SQLFiddle DEMO
EDIT2 - to get all persons change JOINS a bit at the end:
SELECT pc.Id AS ChildID, pc.Name AS ChildName, r.ParentId, pp.Name AS ParentName
FROM dbo.Person pc
LEFT JOIN CTE_RN r ON pc.id = r.CHildId AND RN =1
LEFT JOIN dbo.Person pp ON pp.id = r.ParentId
SQLFiddle DEMo
I've used this pattern to associate items in a hierarchy with the item's root node.
Essentially recursing the hierarchies maintaining the values of the root node as additional columns appended to each row. Hope this helps.
with allRows as (
select ItemId, ItemName, ItemId [RootId],ItemName [RootName]
from parentChildTable
where ParentItemId is null
union all
select a1.ItemId,a1.ItemName,a2.[RootId],a2.[RootName]
from parentChildTable a1
join allRows a2 on a2.ItemId = a1.ParentItemId
)
select * from allRows
To find all top-level parents, use a query like:
select p.Name
from Person p
where not exists
(select null
from RelationHierarchy r
where r.ChildId = p.Id)
SQLFiddle here.
To find the top-level parent of a specific child, use:
with cte as
(select t.ParentId TopParent, t.ChildId
from RelationHierarchy t
left join RelationHierarchy p on p.ChildId = t.ParentId
where p.ChildId is null
union all
select t.TopParent TopParent, c.ChildId
from cte t
join RelationHierarchy c on t.ChildId = c.ParentId)
select p.name
from cte h
join Person p on h.TopParent = p.Id
where h.ChildId=3 /*or whichever child is required*/
SQLFiddle here.
Try this.
The recursive CTE will find the person and walk up the hierarchy until it finds no parent.
-- This CTE will find the ancestors along with a measure of how far up
-- the hierarchy each ancestor is from the selected person.
with ancestor as (
select ParentId as AncestorId, 0 as distance
from RelationHierarchy
where CHildId = ?
union all
select h.ParentId, a.distance + 1
from ancestor a inner join RelationHierarchy rh on a.AncestorId = rh.ChildId
)
select AncestorId
from ancestor
where distance = (select max(distance) from ancestor)
Something like this will work for above example:
SELECT ParentId FROM RelationHierarchy
WHERE ParentId NOT IN (SELECT CHildId FROM RelationHierarchy)
The only way you can do this in "standard" SQL is to assume a maximum depth for the tree, and then do joins for each level. The following gets the top level id:
select rh1.ChildId,
coalesce(rh4.parentid, rh3.parentid, rh2.parentid, rh1.parentid) as topLevel
from RelationshipHierarchy rh1 left outer join
RelationshipHierarchy rh2
on rh1.parentId = rh2.childId left outer join
RelationshipHierarchy rh3
on rh2.parentId = rh3.childId left outer join
RelationshipHierarchy rh4
on rh3.parentId = rh4.childId;
If you want the name, you can just join it in:
select rh1.ChildId,
coalesce(rh4.parentid, rh3.parentid, rh2.parentid, rh1.parentid) as topLevel,
p.name
from RelationshipHierarchy rh1 left outer join
RelationshipHierarchy rh2
on rh1.parentId = rh2.childId left outer join
RelationshipHierarchy rh3
on rh2.parentId = rh3.childId left outer join
RelationshipHierarchy rh4
on rh3.parentId = rh4.childId left outer join
Person p
on p.id = coalesce(rh4.parentid, rh3.parentid, rh2.parentid, rh1.parentid);
Get all top parents using path
path format: rootId/.../parentId/nodeId/
select t1.path from nodes t1 inner join nodes t2
on t1.path like t2.path+'%'
group by t1.path
having len(t1.path)-len(replace(t1.path, '/', ''))
=min(len(t2.path)-len(replace(t2.path, '/', '')))
Give this a go:
select id,name
from person p
where not exists
(
select 1
from relationhierarchy r
where r.childid= p.id
)
and exists
(
select 1
from relationhierarchy r
where r.parentid= p.id
)
It is not enough to just see if a child id exists as in your example E is present in the person table but not in the relationshiphierarchy table.
WITH CTE_MyTable AS (
SELECT Id, ParentId, NULL As RootParent, 1 As Lvl
FROM dbo.Ministry
UNION ALL
SELECT a.id, b.ParentId, a.ParentId As RootParent, Lvl + 1
FROM CTE_MyTableAS a INNER JOIN
dbo.MyTableAS b ON a.ParentId = b.Id
)
, CTE_Ministry_RN AS (
SELECT Id, RootParent, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Lvl DESC) RN
FROM CTE_Ministry
)
SELECT Id, ISNULL(RootParent, Id) As RootParent
FROM CTE_Ministry_RN
WHERE RN = 1

SQL recursive query that gets all ancestors of an item

ID parent_id name
---------------------
1 2 first
2 4 second
3 3 third
4 5 fourth
5 - fifth
Ancestors list of first should be (2, 4, 5)
with name_tree as (
select id, parent_id, name
from the_unknown_table
where id = 1 -- this is the starting point you want in your recursion
union all
select c.id, c.parent_id, c.name
from the_unknown_table c
join name_tree p on p.parent_id = c.id -- this is the recursion
)
select *
from name_tree
where id <> 1; -- exclude the starting point from the overall result
SQLFiddle: http://sqlfiddle.com/#!3/87d0c/1
You can use something like this:
with parents as
(
select ID, parent_ID
from t
where parent_ID is not null
union all
select p.ID, t.parent_ID
from parents p
inner join t on p.parent_ID = t.ID
and t.parent_ID is not null
and t.ID <> t.parent_ID
)
select *
, parents = '(' + stuff
(
(
select ', ' + cast(p.parent_ID as varchar(100))
from parents p
where t.ID = p.ID
for xml path('')
), 1, 2, ''
) + ')'
from t
order by ID
SQL Fiddle with demo.
This combines two very common T-SQL techniques - using a CTE to get a hierarchy and using FOR XML PATH to get a CSV list.