Consider the following (1:N) relationship:
[entity: user] <------ rid key ------> [entity: rid].
consider the data in both tables as:
select * from user;
user-id rid-key
a-basa a
b-basa b
a.a-basa a.a
a.b-basa a.b
a.a.a-basa a.a.a
a.a.b-basa a.a.b
a.b.a-basa a.b.a
a.b.b-basa a.b.b
a.b.b.a-basa a.b.b.a
a.b.b.b-basa a.b.b.b
select * from rid;
rid-key parent-rid enabled
a null true
b null true
a.a a true
a.b a false
a.a.a a.a true
a.b.a a.b true
a.b.b a.b true
a.b.b.a a.b.b true
......
n rows
I need to design a single query (not stored procedure) which will input a user-id, and the following facts are considered:
If an user is given access to a rid, then it can also access the parent rid of the rid given – the rid itself is enabled (enabled = true).
This should continue till we reach the root rid, ie. parent rid property is null.
In above example, the list of accessible rid for the user 'a.b.b.a-basa' will be:
a.b.b.a
a.b.b
a.b
and for a.a.a-basa:
a.a.a
a.a
a
can we get this list using a single query? Any sql vendor is fine.
There are several models for Hierarchical data. Most models (like the Adjacency List) require some sort of recursion for some queries. With your design that uses the Materialized Path model, what you want is possible without a recursive query.
Tested in MySQL (that has no recursive queries), at SQL-fiddle test-mysql. It can be easily converted for other DBMS, if you modify the string concatenation part:
It uses this view, which is not strictly needed but it shows that the
user.user_idis storing data that you already have in therid_keycolumn.One more note is that the above query does not use the
parent_ridcolumn at all. And that I’m sure it can be further improved.