Advertisement

03.01.2007 at 05:39PM PST, ID: 22423091
[x]
Attachment Details

Recursive relationships

Asked by gripe in PostgreSQL Database, Oracle Database, SQL Query Syntax

Tags: recursive, relationship

I have a table like this:

CREATE TABLE Foo (
     id1 integer,
     id2 integer
);

Each row is unique and is used to store the relationship between two entities. So, for instance, given the data:

INSERT INTO Foo VALUES (1, 2);
INSERT INTO Foo VALUES (1, 3);
INSERT INTO Foo VALUES (4, 1);
INSERT INTO Foo VALUES (2, 5);
INSERT INTO Foo VALUES (1, 2);
INSERT INTO Foo VALUES (6, 1);
INSERT INTO Foo VALUES (4, 7);

I can use the following query to find out all of the relationships that one id has:

SELECT id1 FROM Foo WHERE id2 = 1
UNION
SELECT id2 FROM Foo WHERE id1 = 1;

The output would be:

2
3
4
6

Now, let's say I wanted to find all relationships for all of the relationships for 1 so that the query returned all ids that where uniquely related to each relation of the specified id. The output should be:

5
7

Is there a single query that will get me those results or do I need to write a recursive stored procedure to find each of the relations for each subrelations?Start Free Trial
[+][-]03.01.2007 at 05:40PM PST, ID: 18637599

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]03.02.2007 at 04:44AM PST, ID: 18639759

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]03.02.2007 at 08:38AM PST, ID: 18642153

Assisted solutions are selected by the member who asked the question as a comment that contributed to their question's solution.

Start your 7-day free trial to view this Assisted Solution or ask the Experts your question.

 
[+][-]03.02.2007 at 08:38AM PST, ID: 18642154

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]03.04.2007 at 12:01PM PST, ID: 18650993

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: PostgreSQL Database, Oracle Database, SQL Query Syntax
Tags: recursive, relationship
Sign Up Now!
Solution Provided By: rbrooker
Participating Experts: 3
Solution Grade: A
 
 
 
Loading Advertisement...
20080716-EE-VQP-32