SQL:匹配表中的父项和子项

时间:2017-07-31 17:58:00

标签: sql sql-server

首次使用SQL。我有表Person(personID, name, parentID1, parentID2)。家长包括在表中。我必须返回表格结果(孩子,父母)。如果孩子没有父母,则不包括在内。如果孩子有两个父母,孩子会在每个父母旁边列出两次。

我正在使用的确切表格:

CREATE TABLE dbo.[Person]
(
    personID INT NOT NULL PRIMARY KEY,
    name VARCHAR(50),
    parentID1 INT,
    parentID2 INT,
    gender VARCHAR(10)
)

INSERT INTO dbo.Person

SELECT 25, 'Jack', 255, NULL, 'Male'
UNION
SELECT 13, 'Jill', 100, 101, 'Female'
UNION
SELECT 82, 'Adam', NULL, 200, 'Male'
UNION
SELECT 100, 'Jeff', NULL, NULL, 'Male'
UNION
SELECT 101, 'June', NULL, NULL, 'Female'
UNION
SELECT 200, 'Shirley', NULL, NULL, 'Female'
UNION
SELECT 155, 'Alice', 255, NULL, 'Female'
UNION
SELECT 255, 'Tom', NULL, NULL, 'Male'
UNION
SELECT 19, 'Jake', 100,101, 'Male'

4 个答案:

答案 0 :(得分:0)

联盟声明应该足够了:

    SELECT PersonID AS Child
          ,ParentID1 AS Parent
    FROM dbo.Person p1
    WHERE ParentID1 IS NOT NULL
    UNION
    SELECT PersonID AS Child
          ,ParentID2 AS Parent
    FROM dbo.Person p2
    WHERE ParentID2 IS NOT NULL

答案 1 :(得分:0)

递归连接可以为您提供所需内容。这样的事情应该有效。

select  p1.name as child, 
        p2.name as parent 
from    dbo.[Person] p1 
    join dbo.[Person] p2
        on p1.parentID1 = p2.personID
        or p1.parentID2 = p2.personID
order by p1.name

答案 2 :(得分:0)

听起来你只需要一个自我加入。注意聚合要将父项组合成一行。

select
    max(case when t1.gender = 'Female' then t1.name end) as Mother
    ,max(case when t1.gender = 'Male' then t1.name end) as Father
    ,t2.name as Child
    ,t2.gender as ChildGender
from 
    Person t2 
    inner join Person t1 on t1.personID = t2.parentID1 or t1.personID = t2.parentID2
group by
    t2.name 
    ,t2.gender

DEMO

<强>返回

+----+---------+--------+-------+-------------+
|    | Mother  | Father | Child | ChildGender |
+----+---------+--------+-------+-------------+
|  1 | NULL    | Tom    | Alice | Female      |
|  2 | June    | Jeff   | Jill  | Female      |
|  3 | Shirley | NULL   | Adam  | Male        |
|  4 | NULL    | Tom    | Jack  | Male        |
|  5 | June    | Jeff   | Jake  | Male        |

答案 3 :(得分:0)

[请使用输出检查图像]

SELECT NAME,parentID1 AS parentID FROM person WHERE parentID1 IS NOT NULL UNION

SELECT NAME,parentID2 AS parentID FROM person WHERE parentID2 IS NOT NULL;

https://i.stack.imgur.com/uoU2H.png