473,593 Members | 2,794 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Nested Coalescing possible in SQL?

First of all, I apologize if coalescing is not the right term to
describe my problem. I have a tree where each node has the same set of
attributes (is the same entity) but child nodes should inherit
attribute values from parent node.

for example, say I have the following table:

(nodeId int , color varchar, phone varchar) with two rows

5, "GREEN", "555-1212"
7, NULL, "777-5555"
8, NULL, NULL
9, "BLUE", NULL

in addition there is a tree structure that specifies that node 5 is
the parent of node 7, and 7 is the parent of nodes 8 and 9. I know
there is many ways to make trees in SQL but as a simple example let's
say the tree is:

id, parentid
8, 7
9, 7
7, 5

Thus in this case, node 7 inherits the value "GREEN" from node 5 for
attribute "color", but provides its own value "777-5555" for attribute
"phone". Node 8, in turn, inherits "GREEN" for "color" from node 7
(really from node 5 since 7 did not specify its own) and "777-5555"
for "phone" from node 7. Node 9 provides its own value for "color" and
inherits the one for "phone" from Node 7.

So the runtime values in the application are:

Node 5: "GREEN", "555-1212"
Node 7: "GREEN", "777-5555"
Node 8: "GREEN", "777-5555"
Node 9: "BLUE", "777-5555"

Question 1: Is there a single SQL statement that for a given node can
replace the NULLs with inherited values from the parent node?

Question 2: Is there a better way to structure such data in SQL as to
make answer to question 1 possible?

I would restate the problem as follows:

In a nested structure child nodes inherit values from parent nodes _by
reference_ or specify their own. "By reference" is the key word here.
If it wasn't for that you could just duplicate the necessary values
from the parent entitity upon creation.

Thanks!

- Jeff
Jul 20 '05 #1
12 3965

"Jeff Lanfield" <jl***********@ yahoo.com> wrote in message
news:23******** *************** ***@posting.goo gle.com...
First of all, I apologize if coalescing is not the right term to
describe my problem. I have a tree where each node has the same set of
attributes (is the same entity) but child nodes should inherit
attribute values from parent node.

for example, say I have the following table:

(nodeId int , color varchar, phone varchar) with two rows

5, "GREEN", "555-1212"
7, NULL, "777-5555"
8, NULL, NULL
9, "BLUE", NULL

in addition there is a tree structure that specifies that node 5 is
the parent of node 7, and 7 is the parent of nodes 8 and 9. I know
there is many ways to make trees in SQL but as a simple example let's
say the tree is:

id, parentid
8, 7
9, 7
7, 5

Thus in this case, node 7 inherits the value "GREEN" from node 5 for
attribute "color", but provides its own value "777-5555" for attribute
"phone". Node 8, in turn, inherits "GREEN" for "color" from node 7
(really from node 5 since 7 did not specify its own) and "777-5555"
for "phone" from node 7. Node 9 provides its own value for "color" and
inherits the one for "phone" from Node 7.

So the runtime values in the application are:

Node 5: "GREEN", "555-1212"
Node 7: "GREEN", "777-5555"
Node 8: "GREEN", "777-5555"
Node 9: "BLUE", "777-5555"

Question 1: Is there a single SQL statement that for a given node can
replace the NULLs with inherited values from the parent node?

Question 2: Is there a better way to structure such data in SQL as to
make answer to question 1 possible?

I would restate the problem as follows:

In a nested structure child nodes inherit values from parent nodes _by
reference_ or specify their own. "By reference" is the key word here.
If it wasn't for that you could just duplicate the necessary values
from the parent entitity upon creation.


It looks easy. Find a closest node in the chain of ancestors that has
property not NULL.
Jul 20 '05 #2
jl***********@y ahoo.com (Jeff Lanfield) wrote in message news:<23******* *************** ****@posting.go ogle.com>...
First of all, I apologize if coalescing is not the right term to
describe my problem. I have a tree where each node has the same set of
attributes (is the same entity) but child nodes should inherit
attribute values from parent node.

for example, say I have the following table:

(nodeId int , color varchar, phone varchar) with two rows

5, "GREEN", "555-1212"
7, NULL, "777-5555"
8, NULL, NULL
9, "BLUE", NULL

in addition there is a tree structure that specifies that node 5 is
the parent of node 7, and 7 is the parent of nodes 8 and 9. I know
there is many ways to make trees in SQL but as a simple example let's
say the tree is:ancestor a

id, parentid
8, 7
9, 7
7, 5

Thus in this case, node 7 inherits the value "GREEN" from node 5 for
attribute "color", but provides its own value "777-5555" for attribute
"phone". Node 8, in turn, inherits "GREEN" for "color" from node 7
(really from node 5 since 7 did not specify its own) and "777-5555"
for "phone" from node 7. Node 9 provides its own value for "color" and
inherits the one for "phone" from Node 7.

So the runtime values in the application are:

Node 5: "GREEN", "555-1212"
Node 7: "GREEN", "777-5555"
Node 8: "GREEN", "777-5555"
Node 9: "BLUE", "777-5555"

Question 1: Is there a single SQL statement that for a given node can
replace the NULLs with inherited values from the parent node?

Question 2: Is there a better way to structure such data in SQL as to
make answer to question 1 possible?

I would restate the problem as follows:

In a nested structure child nodes inherit values from parent nodes _by
reference_ or specify their own. "By reference" is the key word here.
If it wasn't for that you could just duplicate the necessary values
from the parent entitity upon creation.

Thanks!

- Jeff

If you would like to do it in a single query, you will have to extend
your tree, or if your db supports it, you can use recursion. There are
several ways of extending your tree, nested set, transitive closure,
etc. If you google comp.database and comp.database.t heory you will
find several threads regarding this.

Assuming you can "calculate" the set of ancestors for any given node,
define the suspects as "ancestors with property p". The property you
are looking for can be found in the suspect with the largest depth*.

*depth = number of ancestors
HTH
/Lennart
Jul 20 '05 #3
>> Question 2: Is there a better way to structure such data in SQL as
to make answer to question 1 possible? <<

Here is the link on Amazon.com for my new book on "Trees & Hierarchies
in SQL"

http://www.amazon.com/exec/obidos/tg...roduct-details

The classic scenario calls for a root class with all the common
attributes and then specialized sub-classes under it. As an example,
let's take the class of Vehicles and find an industry standard
identifier (VIN), and add two mutually exclusive sub-classes, Sport
utility vehicles and sedans ('SUV', 'SED').

CREATE TABLE Vehicles
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) NOT NULL
CHECK(vehicle_t ype IN ('SUV', 'SED')),
UNIQUE (vin, vehicle_type),
..);

Notice the overlapping candidate keys. I then use a compound candidate
key (vin, vehicle_type) and a constraint in each sub-class table to
assure that the vehicle_type is locked and agrees with the Vehicles
table. Add some DRI actions and you are done:

CREATE TABLE SUV
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT 'SUV' NOT NULL
CHECK(vehicle_t ype = 'SUV'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Vehicles(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

CREATE TABLE Sedans
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT 'SED' NOT NULL
CHECK(vehicle_t ype = 'SED'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Vehicles(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

I can continue to build a hierarchy like this. For example, if I had
a Sedans table that broke down into two-door and four-door sedans, I
could a schema like this:

CREATE TABLE Sedans
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT 'SED' NOT NULL
CHECK(vehicle_t ype IN ('2DR', '4DR', 'SED')),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Vehicles(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

CREATE TABLE TwoDoor
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT '2DR' NOT NULL
CHECK(vehicle_t ype = '2DR'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Sedans(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

CREATE TABLE FourDoor
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT '4DR' NOT NULL
CHECK(vehicle_t ype = '4DR'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Sedans (vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

The idea is to build a chain of identifiers and types in a UNIQUE()
constraint that go up the tree when you use a REFERENCES constraint.
Obviously, you can do variants of this trick to get different class
structures.

If an entity doesn't have to be exclusively one subtype, you play with
the root of the class hierarchy:

CREATE TABLE Vehicles
(vin CHAR(17) NOT NULL,
vehicle_type CHAR(3) NOT NULL
CHECK(vehicle_t ype IN ('SUV', 'SED')),
PRIMARY KEY (vin, vehicle_type),
..);

Now start hiding all this stuff in VIEWs immediately and add an
INSTEAD OF trigger to those VIEWs.
Jul 20 '05 #4
jl***********@y ahoo.com (Jeff Lanfield) wrote in message news:<23******* *************** ****@posting.go ogle.com>...

[...]

So say the tree is specified like this:

(nodeId int, parentId int, color varchar, phone varchar)

5, 0,"GREEN", "555-1212"
7, 5, NULL, "777-5555"
8, 7 NULL, NULL
9, 7 "BLUE", NULL
That is: node 7 inherits values from 5. Nodes 8,9 inherit values from
7. Node 5 is the top level node.

I want to run a query that would give the following result set:

select nodeId, color, phone from ...

5,"GREEN", "555-1212"
7,"GREEN", "777-5555"
8,"GREEN", "777-5555"
9,"BLUE", "777-5555"

Can such a query be constructed?

If you dont have a maximum depth of your tree (and cannot use
recursion), then no. The reason is that you cannot express queries
like "gimmie the ancestors of x". What you need to do is to inform
your system that 5 is an ancestor of 9. There are several ways of
doing this. Troels Arvin has a page with links to articles on the
subject:

http://troels.arvin.dk/db/rdbms/links/#hierarchical

1. Nested set: google for Celko and nested. There are also variants of
this.
2. Store the path in each node. In your case something like:

5,'',"GREEN", "555-1212"
7,'5',"GREEN", "777-5555"
8,'5.7',"GREEN" , "777-5555"
9,'5.7',"BLUE", "777-5555"

In your case I dont think this is an option

3. Store a separate ancestor relation. In your case

create table ancestor (
nodeid int not null
references tree,
ancestorid int not null
references tree,
primary key (nodeid, ancestorid)
);

insert into ancestor values (7,5), (8,7), (8,5), (9,7), (9,5);

Main drawback is that you have to maintain this relation as you
modifies your tree. I have some notes on how that can be achieved:

http://fungus.teststation.com/~jon/t...eeHandling.htm

Anyhow, once you have a way of asking for ancestors for a given node,
you can do what you want in a single query, namely:

find the ancestor at the largest depth with property p

Assuming the following ddl

create table tree (
nodeid int not null primary key,
parent int not null
references tree
on delete restrict
);

create table data (
nodeid int not null primary key
references tree
on delete cascade,
color varchar(10),
phone varchar(10)
);

insert into tree values (5,5), (7,5), (8,7), (9,7);
insert into data values (5, 'GREEN', '555-1212'), (7, NULL,
'777-5555'), (8, NUL
L, NULL), (9, 'BLUE', NULL);

create table ancestor (
nodeid int not null
references tree,
ancestorid int not null
references tree,
primary key (nodeid, ancestorid)
);

insert into ancestor values (7,5), (8,7), (8,5), (9,7), (9,5);

You could use a query like:

with suspects (nodeid, suspectid, depth) as (
select
a.nodeid, a.ancestorid,
(select count(1) from ancestor where nodeid = a.ancestorid) as
depth
from ancestor a, data d
where a.ancestorid = d.nodeid
and d.color is not null
union all
select
d.nodeid, d.nodeid,
(select count(1) from ancestor where nodeid = d.nodeid) as
depth
from data d
where d.color is not null
and not exists (
select 1 from ancestor where ancestorid = d.nodeid
)
)
select s.nodeid, d.color from suspects s, data d
where d.nodeid = s.suspectid
and depth = (select max(depth) from suspects where nodeid =
s.nodeid)

NODEID COLOR
----------- ----------
7 GREEN
8 GREEN
9 BLUE

3 record(s) selected.

As you can see node 5 is missing, but I'll leave that for you ;-)
HTH
/Lennart

- Jeff

Jul 20 '05 #5
Thanks --CELKO--, this is a very useful suggestion and I will keep it
in mind. However, it is designed to handle an hiearchy of types (e.g.
representing class hierarchy). My case is slightly different: I don't
have types and subtypes, I have only one table representing one
entity. The inheritance of values is in the following sense: if an
entity instance (one row) does not specify a value for one of its
fields it should inherit the values from its nearest parent that does
have a value for this field. Note that the immediate parent may have a
NULL in that field too, so you'd have to go the parent's parent and so
on till you find a non-NULL value for the field in question. I think I
should be able to use COALESCE to do it somehow but I can't come up
with a *single* query.

So the exact example is this. I have a tree structure of values, there
is only one type of entity. Per Lennart's suggestion I'm keeping the
full path pre-computed for the sake of simplicity. There is only this
one table:

(nodeId int, varchar parent_path, color varchar, phone varchar)

5, "0", "GREEN", "555-1212"
7, "0,5", NULL, "777-5555"
8, "0,5,7" NULL, NULL
9, "0,5,7" "BLUE", NULL

I want to run a query that would give the following result set:

select nodeId, color, phone from ...

5,"GREEN", "555-1212"
7,"GREEN", "777-5555"
8,"GREEN", "777-5555"
9,"BLUE", "777-5555"

Is it possible to have such a query?

- Jeff


jc*******@earth link.net (--CELKO--) wrote in message news:<18******* *************** ****@posting.go ogle.com>...
Question 2: Is there a better way to structure such data in SQL as

to make answer to question 1 possible? <<

Here is the link on Amazon.com for my new book on "Trees & Hierarchies
in SQL"

http://www.amazon.com/exec/obidos/tg...roduct-details

The classic scenario calls for a root class with all the common
attributes and then specialized sub-classes under it. As an example,
let's take the class of Vehicles and find an industry standard
identifier (VIN), and add two mutually exclusive sub-classes, Sport
utility vehicles and sedans ('SUV', 'SED').

CREATE TABLE Vehicles
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) NOT NULL
CHECK(vehicle_t ype IN ('SUV', 'SED')),
UNIQUE (vin, vehicle_type),
..);

Notice the overlapping candidate keys. I then use a compound candidate
key (vin, vehicle_type) and a constraint in each sub-class table to
assure that the vehicle_type is locked and agrees with the Vehicles
table. Add some DRI actions and you are done:

CREATE TABLE SUV
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT 'SUV' NOT NULL
CHECK(vehicle_t ype = 'SUV'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Vehicles(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

CREATE TABLE Sedans
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT 'SED' NOT NULL
CHECK(vehicle_t ype = 'SED'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Vehicles(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

I can continue to build a hierarchy like this. For example, if I had
a Sedans table that broke down into two-door and four-door sedans, I
could a schema like this:

CREATE TABLE Sedans
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT 'SED' NOT NULL
CHECK(vehicle_t ype IN ('2DR', '4DR', 'SED')),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Vehicles(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

CREATE TABLE TwoDoor
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT '2DR' NOT NULL
CHECK(vehicle_t ype = '2DR'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Sedans(vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

CREATE TABLE FourDoor
(vin CHAR(17) NOT NULL PRIMARY KEY,
vehicle_type CHAR(3) DEFAULT '4DR' NOT NULL
CHECK(vehicle_t ype = '4DR'),
UNIQUE (vin, vehicle_type),
FOREIGN KEY (vin, vehicle_type)
REFERENCES Sedans (vin, vehicle_type)
ON UPDATE CASCADE
ON DELETE CASCADE,
..);

The idea is to build a chain of identifiers and types in a UNIQUE()
constraint that go up the tree when you use a REFERENCES constraint.
Obviously, you can do variants of this trick to get different class
structures.

If an entity doesn't have to be exclusively one subtype, you play with
the root of the class hierarchy:

CREATE TABLE Vehicles
(vin CHAR(17) NOT NULL,
vehicle_type CHAR(3) NOT NULL
CHECK(vehicle_t ype IN ('SUV', 'SED')),
PRIMARY KEY (vin, vehicle_type),
..);

Now start hiding all this stuff in VIEWs immediately and add an
INSTEAD OF trigger to those VIEWs.

Jul 20 '05 #6
Thanks Lennart. I think your third suggestion might do the trick. If
you have a chance to answer I'm curious:

1) Why do you think storing the path (suggestion #2) is not an option?
Or if it is option, why is it a bad idea compared to storing a
separate ancestor relation? (aside from the usual normal form
reasoning)

2) How would you structure the query if you stored the path
(suggestion #2).

Thanks!

- Jeff

le*****@kommuni cera.umea.se (Lennart Jonsson) wrote in message news:<6d******* *************** **@posting.goog le.com>...
jl***********@y ahoo.com (Jeff Lanfield) wrote in message news:<23******* *************** ****@posting.go ogle.com>...

[...]

So say the tree is specified like this:

(nodeId int, parentId int, color varchar, phone varchar)

5, 0,"GREEN", "555-1212"
7, 5, NULL, "777-5555"
8, 7 NULL, NULL
9, 7 "BLUE", NULL
That is: node 7 inherits values from 5. Nodes 8,9 inherit values from
7. Node 5 is the top level node.

I want to run a query that would give the following result set:

select nodeId, color, phone from ...

5,"GREEN", "555-1212"
7,"GREEN", "777-5555"
8,"GREEN", "777-5555"
9,"BLUE", "777-5555"

Can such a query be constructed?


If you dont have a maximum depth of your tree (and cannot use
recursion), then no. The reason is that you cannot express queries
like "gimmie the ancestors of x". What you need to do is to inform
your system that 5 is an ancestor of 9. There are several ways of
doing this. Troels Arvin has a page with links to articles on the
subject:

http://troels.arvin.dk/db/rdbms/links/#hierarchical

1. Nested set: google for Celko and nested. There are also variants of
this.
2. Store the path in each node. In your case something like:

5,'',"GREEN", "555-1212"
7,'5',"GREEN", "777-5555"
8,'5.7',"GREEN" , "777-5555"
9,'5.7',"BLUE", "777-5555"

In your case I dont think this is an option

3. Store a separate ancestor relation. In your case

create table ancestor (
nodeid int not null
references tree,
ancestorid int not null
references tree,
primary key (nodeid, ancestorid)
);

insert into ancestor values (7,5), (8,7), (8,5), (9,7), (9,5);

Main drawback is that you have to maintain this relation as you
modifies your tree. I have some notes on how that can be achieved:

http://fungus.teststation.com/~jon/t...eeHandling.htm

Anyhow, once you have a way of asking for ancestors for a given node,
you can do what you want in a single query, namely:

find the ancestor at the largest depth with property p

Assuming the following ddl

create table tree (
nodeid int not null primary key,
parent int not null
references tree
on delete restrict
);

create table data (
nodeid int not null primary key
references tree
on delete cascade,
color varchar(10),
phone varchar(10)
);

insert into tree values (5,5), (7,5), (8,7), (9,7);
insert into data values (5, 'GREEN', '555-1212'), (7, NULL,
'777-5555'), (8, NUL
L, NULL), (9, 'BLUE', NULL);

create table ancestor (
nodeid int not null
references tree,
ancestorid int not null
references tree,
primary key (nodeid, ancestorid)
);

insert into ancestor values (7,5), (8,7), (8,5), (9,7), (9,5);

You could use a query like:

with suspects (nodeid, suspectid, depth) as (
select
a.nodeid, a.ancestorid,
(select count(1) from ancestor where nodeid = a.ancestorid) as
depth
from ancestor a, data d
where a.ancestorid = d.nodeid
and d.color is not null
union all
select
d.nodeid, d.nodeid,
(select count(1) from ancestor where nodeid = d.nodeid) as
depth
from data d
where d.color is not null
and not exists (
select 1 from ancestor where ancestorid = d.nodeid
)
)
select s.nodeid, d.color from suspects s, data d
where d.nodeid = s.suspectid
and depth = (select max(depth) from suspects where nodeid =
s.nodeid)

NODEID COLOR
----------- ----------
7 GREEN
8 GREEN
9 BLUE

3 record(s) selected.

As you can see node 5 is missing, but I'll leave that for you ;-)
HTH
/Lennart

- Jeff

Jul 20 '05 #7
le*****@kommuni cera.umea.se (Lennart Jonsson) wrote in message news:<6d******* *************** **@posting.goog le.com>...
jl***********@y ahoo.com (Jeff Lanfield) wrote in message news:<23******* *************** ****@posting.go ogle.com>...


[...]

Hmmm, I must have been just a little bit tired there ;-) Should read
(diff in snd part of union):

with suspects (nodeid, suspectid, depth) as (
select
a.nodeid, a.ancestorid,
(select count(1) from ancestor where nodeid = a.ancestorid)
as depth
from ancestor a, data d
where a.ancestorid = d.nodeid
and d.color is not null
union all
select
t.nodeid, t.nodeid,
(select count(1) from ancestor where nodeid = t.nodeid) as
depth
from data d, tree t
where d.nodeid = t.nodeid
and d.color is not null
)
select s.nodeid, d.color from suspects s, data d
where d.nodeid = s.suspectid
and depth = (select max(depth) from suspects where nodeid =
s.nodeid)
;
NODEID COLOR
----------- ----------
5 GREEN
7 GREEN
8 GREEN
9 BLUE
/Lennart
Jul 20 '05 #8
jl***********@y ahoo.com (Jeff Lanfield) wrote in message news:<23******* *************** ***@posting.goo gle.com>...
Thanks Lennart. I think your third suggestion might do the trick. If
you have a chance to answer I'm curious:

1) Why do you think storing the path (suggestion #2) is not an option?
Or if it is option, why is it a bad idea compared to storing a
separate ancestor relation? (aside from the usual normal form
reasoning)

Since youre mainly concerned in retrieving ancestors, (not
investigating subtree
), I think it is a bit clumsy. Assume that you have a node x with path
1.2.3.56.89.112 and want to investigate which nodes in the path that
have property p. How would you do that? Subtree queries are much
easier since you can query: where path like '1.2.4.6.%'

2) How would you structure the query if you stored the path
(suggestion #2).

I would figure out a way to retrive ancestors and then use the same
way.

If I where in your shoes I would encapsulate the ancestor stuff in
views or table functions, and then use those in my queries. If you
decide to go for another aproach, you rewrite the functions/views and
can continue to use the queries. Simple example using table functions
in db2:
-- ancestor table aproach

CREATE FUNCTION SUBTREE (ID INTEGER)
RETURNS TABLE (NODEID INTEGER)
LANGUAGE SQL
READS SQL DATA
NO EXTERNAL ACTION
DETERMINISTIC
RETURN
select nodeid from ancestor where ancestorid = ID
@

CREATE FUNCTION SUBTREE_SELF (ID INTEGER)
RETURNS TABLE (NODEID INTEGER)
LANGUAGE SQL
READS SQL DATA
NO EXTERNAL ACTION
DETERMINISTIC
RETURN
select s.nodeid from table(subtree(I D)) as s
union all
values (ID)
@
-- changed my mind decided to go for path aproach instead

drop ...

CREATE FUNCTION SUBTREE (ID INTEGER)
RETURNS TABLE (NODEID INTEGER)
LANGUAGE SQL
READS SQL DATA
NO EXTERNAL ACTION
DETERMINISTIC
RETURN
select nodeid from tree where path like (ID || '.%')

etc

The same goes for depth

As a bonus it will simplify your original query. I.e

with suspects (nodeid, ancestorid, depth) as (
select
ps.nodeid, ps.ancestorid, depth_func(ps.n odeid) as depth
from data d, tree t, table(path_self (t.nodeid)) ps
where ps.ancestorid = d.nodeid and d.color is not null
)
select ...

HTH
/Lennart
Thanks!

- Jeff

le*****@kommuni cera.umea.se (Lennart Jonsson) wrote in message news:<6d******* *************** **@posting.goog le.com>...
jl***********@y ahoo.com (Jeff Lanfield) wrote in message news:<23******* *************** ****@posting.go ogle.com>...

[...]

So say the tree is specified like this:

(nodeId int, parentId int, color varchar, phone varchar)

5, 0,"GREEN", "555-1212"
7, 5, NULL, "777-5555"
8, 7 NULL, NULL
9, 7 "BLUE", NULL

That is: node 7 inherits values from 5. Nodes 8,9 inherit values from
7. Node 5 is the top level node.

I want to run a query that would give the following result set:

select nodeId, color, phone from ...

5,"GREEN", "555-1212"
7,"GREEN", "777-5555"
8,"GREEN", "777-5555"
9,"BLUE", "777-5555"

Can such a query be constructed?


If you dont have a maximum depth of your tree (and cannot use
recursion), then no. The reason is that you cannot express queries
like "gimmie the ancestors of x". What you need to do is to inform
your system that 5 is an ancestor of 9. There are several ways of
doing this. Troels Arvin has a page with links to articles on the
subject:

http://troels.arvin.dk/db/rdbms/links/#hierarchical

1. Nested set: google for Celko and nested. There are also variants of
this.
2. Store the path in each node. In your case something like:

5,'',"GREEN", "555-1212"
7,'5',"GREEN", "777-5555"
8,'5.7',"GREEN" , "777-5555"
9,'5.7',"BLUE", "777-5555"

In your case I dont think this is an option

3. Store a separate ancestor relation. In your case

create table ancestor (
nodeid int not null
references tree,
ancestorid int not null
references tree,
primary key (nodeid, ancestorid)
);

insert into ancestor values (7,5), (8,7), (8,5), (9,7), (9,5);

Main drawback is that you have to maintain this relation as you
modifies your tree. I have some notes on how that can be achieved:

http://fungus.teststation.com/~jon/t...eeHandling.htm

Anyhow, once you have a way of asking for ancestors for a given node,
you can do what you want in a single query, namely:

find the ancestor at the largest depth with property p

Assuming the following ddl

create table tree (
nodeid int not null primary key,
parent int not null
references tree
on delete restrict
);

create table data (
nodeid int not null primary key
references tree
on delete cascade,
color varchar(10),
phone varchar(10)
);

insert into tree values (5,5), (7,5), (8,7), (9,7);
insert into data values (5, 'GREEN', '555-1212'), (7, NULL,
'777-5555'), (8, NUL
L, NULL), (9, 'BLUE', NULL);

create table ancestor (
nodeid int not null
references tree,
ancestorid int not null
references tree,
primary key (nodeid, ancestorid)
);

insert into ancestor values (7,5), (8,7), (8,5), (9,7), (9,5);

You could use a query like:

with suspects (nodeid, suspectid, depth) as (
select
a.nodeid, a.ancestorid,
(select count(1) from ancestor where nodeid = a.ancestorid) as
depth
from ancestor a, data d
where a.ancestorid = d.nodeid
and d.color is not null
union all
select
d.nodeid, d.nodeid,
(select count(1) from ancestor where nodeid = d.nodeid) as
depth
from data d
where d.color is not null
and not exists (
select 1 from ancestor where ancestorid = d.nodeid
)
)
select s.nodeid, d.color from suspects s, data d
where d.nodeid = s.suspectid
and depth = (select max(depth) from suspects where nodeid =
s.nodeid)

NODEID COLOR
----------- ----------
7 GREEN
8 GREEN
9 BLUE

3 record(s) selected.

As you can see node 5 is missing, but I'll leave that for you ;-)
HTH
/Lennart

- Jeff

Jul 20 '05 #9
Jan
e.g. in Oracle 9i,

you can:

Creating demo data

CREATE TABLE T
(
CHILD_ID NUMBER,
PARENT_ID NUMBER,
ATTR1 VARCHAR2(10),
ATTR2 VARCHAR2(10)
)

INSERT INTO T VALUES (1 NULL,'A','000') ;
INSERT INTO T VALUES (2,1, NULL, '111');
INSERT INTO T VALUES (3,1, 'B', NULL);
INSERT INTO T VALUES (4,2, NULL, NULL);
INSERT INTO T VALUES (5, 2, 'C', '999');
INSERT INTO T VALUES (6, 5, NULL, NULL);

and the query is (it is too ugly with INSTR/SUBSTR, but maybe faster
then an inline query per each attribute with another CONNECT BY):

------------------
SELECT child_id,PARENT _ID,attr1,attr2 ,tree_path,
RTRIM(SUBSTR(al l_attr1,INSTR(a ll_attr1,'/',-1,2)+1),'/')
inherit_attr1,
RTRIM(SUBSTR(al l_attr2,INSTR(a ll_attr2,'/',-1,2)+1),'/')
inherit_attr2
FROM

(SELECT child_id,parent _id,attr1,attr2 ,
SYS_CONNECT_BY_ PATH(TO_CHAR(ch ild_id), '/') tree_path,
CASE
WHEN attr1 IS NOT NULL THEN '/'||attr1||'/'
ELSE REPLACE('/'||SYS_CONNECT_ BY_PATH(attr1,'/'),'//','/')
END all_attr1,

CASE
WHEN attr2 IS NOT NULL THEN '/'||attr2||'/'
ELSE REPLACE('/'||SYS_CONNECT_ BY_PATH(attr2,'/'),'//','/')
END all_attr2

FROM T
START WITH parent_id IS NULL
CONNECT BY parent_id=PRIOR child_id) v
--------------------------------------------------------

jl***********@y ahoo.com (Jeff Lanfield) wrote in message news:<23******* *************** ****@posting.go ogle.com>...
First of all, I apologize if coalescing is not the right term to
describe my problem. I have a tree where each node has the same set of
attributes (is the same entity) but child nodes should inherit
attribute values from parent node.

for example, say I have the following table:

(nodeId int , color varchar, phone varchar) with two rows

5, "GREEN", "555-1212"
7, NULL, "777-5555"
8, NULL, NULL
9, "BLUE", NULL

in addition there is a tree structure that specifies that node 5 is
the parent of node 7, and 7 is the parent of nodes 8 and 9. I know
there is many ways to make trees in SQL but as a simple example let's
say the tree is:

id, parentid
8, 7
9, 7
7, 5

Thus in this case, node 7 inherits the value "GREEN" from node 5 for
attribute "color", but provides its own value "777-5555" for attribute
"phone". Node 8, in turn, inherits "GREEN" for "color" from node 7
(really from node 5 since 7 did not specify its own) and "777-5555"
for "phone" from node 7. Node 9 provides its own value for "color" and
inherits the one for "phone" from Node 7.

So the runtime values in the application are:

Node 5: "GREEN", "555-1212"
Node 7: "GREEN", "777-5555"
Node 8: "GREEN", "777-5555"
Node 9: "BLUE", "777-5555"

Question 1: Is there a single SQL statement that for a given node can
replace the NULLs with inherited values from the parent node?

Question 2: Is there a better way to structure such data in SQL as to
make answer to question 1 possible?

I would restate the problem as follows:

In a nested structure child nodes inherit values from parent nodes _by
reference_ or specify their own. "By reference" is the key word here.
If it wasn't for that you could just duplicate the necessary values
from the parent entitity upon creation.

Thanks!

- Jeff

Jul 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2651
by: Rich Wahl | last post by:
I am writing a personal application that uses windowListeners, ActionListeners and possible ItemListeners (combo boxes). I have one of the Buttons (ActionListeners) set to have a popup frame/panel to display a Choice. But I would like the Program to not continue on until the user makes their selection from the dropdown/Combo box in the new popup window. Right now, I have it setup so that the Listeners for the main frame are looking...
10
3204
by: nimmi_srivastav | last post by:
Below you will see an example of a nested conditional expression that this colleague of mine loves. He claims that it is more efficient that a multi-level if-else-if structure. Moreover, our complexity analyzer tool supposedly does not pick it up. Is it really more efficient? Personally I find this coding style extremely cryptic, misleading and error-prone. I believe that I have removed all traces of proprietary-ness from this coding...
6
559
by: B0nj | last post by:
I've got a class in which I want to implement a property that operates like an indexer, for the various colors associated with the class. For instance, I want to be able to do 'set' operations like MyClass.MyColors = Color.Green or, a 'get', such as Color forecolor = MyClass.MyColors; I want to use an indexer so I can take parameters, such as the color type (e.g. "Foreground", "Background" etc.). With a single member function I couldn't...
17
3022
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html Why is C# 500% slower than C++ on Nested Loops ??? Will this problem be solved in the future???
11
2532
by: Jon Shemitz | last post by:
The new ?? operator doesn't seem to be in the precedence table in VS.05 <ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_csref/html/214e7b83-1a41-4f7c-9867-64e9c0bab39f.htm>, and I can't seem to find anything about it online. What's the precedence of the ?? operator? , x++, x--, new, typeof, checked, and unchecked - but it doesn't seem "Unary", either. I hope there's not a new category between Unary and Arithmetic!]
9
1995
by: Rich | last post by:
Hi I do like C# 2's new ?? operator, which enables us to code something like: // Ensure someString is not null someString = someString ?? ""; But wouldn't it make a lot of sense to take this a step further and allow a shorthand-assignment equivalent (much like +=, -= and so on)? I.e instead of what we have above, we could just say:
37
2758
by: Tim N. van der Leeuw | last post by:
Hi, The following might be documented somewhere, but it hit me unexpectedly and I couldn't exactly find this in the manual either. Problem is, that I cannot use augmented assignment operators in a nested scope, on variables from the outer scope: PythonWin 2.4.3 (#69, Mar 29 2006, 17:35:34) on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond@skippinet.com.au) -
9
1524
by: Paddy | last post by:
I blogged on finding a new-to-me feature of Python, in that you are allowed to nnest parameter definitions: .... return p0,p1,p2 .... ('Does', 'this', 'work') Ruben commented that there was a poll on this features continued existence taken at PyCon and it could go.
4
2299
by: Wolfgang Draxinger | last post by:
If you know languages like Python or D you know, that nested functions can be really handy. Though some compilers (looking at GCC) provide the extension of nested functions, I wonder, how one could implement an equivalent behaviour with plain C (in this case I'm thinking of the language I'm developing, which shall be converted into C for target compilation). So far I didn't touch the topic "nested functions", since I just don't see an...
0
7936
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7874
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8227
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6646
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5402
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2383
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.