CREATE TABLE PERSON
(
persID INT IDENTITY(1,1) PRIMARY KEY,
persFName VARCHAR(30) NOT NULL,
persLName VARCHAR(30) NOT NULL,
persDOB DATE,
motherID INT FOREIGN KEY REFERENCES person(persID),
fatherID INT FOREIGN KEY REFERENCES person(persID),
persDOD DATE,
persGender CHAR(1),
)
CREATE TABLE COUPLE
(
coupleID INT IDENTITY(1,1) PRIMARY KEY,
alphaSpouse INT NOT NULL FOREIGN KEY REFERENCES person(persID),
omegaSpouse INT NOT NULL FOREIGN KEY REFERENCES person(persID),
coupleStart DATE NOT NULL,
coupleEnd DATE,
)
在过去的几个小时里,我一直在努力弄清楚如何输出每个父亲,母亲和他们所有的孩子。 Trying to get an output like this
我知道如何单独显示一个组,如下所示
SELECT *
FROM person
WHERE persID IN (select fatherID from person
WHERE fatherID IS NOT NULL)
但我不能为我的生活弄清楚如何一起展示它们(彼此相关)。我使用交叉连接吗?联合所有?
答案 0 :(得分:1)
这只是一次加入,好几次。它与couple
表无关:
select (f.persFname + ' ' + f.persLname) as father,
(m.persFName + ' ' + m.persLname) as mother,
(c.persFName + ' ' + c.persLname) as child
from person c join
person m -- mother
on c.motherid = m.persid join
person f -- father
on c.fatherid = f.persid;