Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get family members

Supose the families bellow:

Family Tree

The Build Schema of this is:

create table PersonConn (child int, parent int)
insert into PersonConn values (1,2)
insert into PersonConn values (1,3)
insert into PersonConn values (5,3)
insert into PersonConn values (5,4)
insert into PersonConn values (6,7)
insert into PersonConn values (6,8)
insert into PersonConn values (2,9)
insert into PersonConn values (2,10)
insert into PersonConn values (3,11)
insert into PersonConn values (3,12)

To get the ancestors of a family member I can use recursion as showed bellow:

WITH Childs AS (
    SELECT distinct Child, Parent
    FROM  PersonConn
    WHERE Child = 1
    UNION ALL
    SELECT t2.Child, t2.Parent
    FROM   [Childs] t1
    INNER JOIN  PersonConn t2
        ON  t2.Child = t1.parent
)
SELECT PARENT FROM CHILDS

SQL Fiddle

It will take all the ancestors of selected member (ID 1 in this example), but not the brothers for example. The query goes up only in family tree.

My question is:

How to get all members of a family (sons, parents, grandfathers, uncles, cousins, etc...) starting from a single person?

UPDATE

One method to solve this is a loop that inserts a person in a temporary table. After you could join PersonConn table with this temporary table and inserts other people. Do this until no one is inserted anymore. I am looking for a more efficient (and elegant) way. I have about 200MM records in PersonConn table.

like image 916
Nizam Avatar asked Jul 22 '14 22:07

Nizam


People also ask

Can Google family members see each other?

Family members share the storage space that comes with your Google One plan. But your family group can't see what you store unless you specifically share it with them from Google Drive, Gmail, or Google Photos.

How do I find a member of my family?

Websites like Ancestry.com and FindAGrave.com are a good starting point, and some offer free trials. These sites have access to US census records, birth, marriage, death certificates, and other family trees that may intersect your own.


1 Answers

The solution I found is not good at all. It gives the right answer but is very slow, even for this very small table.

 DECLARE @INCLUIDOS TABLE (ID INT)

 INSERT INTO @INCLUIDOS VALUES(1)

 DECLARE @PAST_QUANT INT = 0
 DECLARE @QUANT INT = 1 

 WHILE @QUANT <> @PAST_QUANT
 BEGIN

     SET @PAST_QUANT = @QUANT

     INSERT INTO @INCLUIDOS
        SELECT PARENT 
        FROM PERSONCONN 
        WHERE CHILD IN (SELECT ID FROM @INCLUIDOS)
            AND PARENT NOT IN (SELECT ID FROM @INCLUIDOS)

    INSERT INTO @INCLUIDOS
        SELECT CHILD
        FROM PERSONCONN
        WHERE PARENT IN (SELECT ID FROM @INCLUIDOS)
            AND CHILD NOT IN (SELECT ID FROM @INCLUIDOS)

    SET @QUANT = (SELECT COUNT(*) FROM @INCLUIDOS)

END

SELECT DISTINCT ID FROM @INCLUIDOS

SQL Fiddle

like image 71
Nizam Avatar answered Sep 21 '22 07:09

Nizam