难以理解 many-to-many 递归
Having difficulty understanding many-to-many recursive
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,
)
在过去的几个小时里,我一直在想办法输出每个父亲、母亲和他们所有的 children。 Trying to get an output like this
我知道如何单独显示一组,如下所示
SELECT *
FROM person
WHERE persID IN (select fatherID from person
WHERE fatherID IS NOT NULL)
但我一辈子都想不出如何将它们一起展示(同时相互关联)。我使用交叉连接吗?联合所有?
这只是一个连接,几次。与 couple
table:
无关
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;
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,
)
在过去的几个小时里,我一直在想办法输出每个父亲、母亲和他们所有的 children。 Trying to get an output like this
我知道如何单独显示一组,如下所示
SELECT *
FROM person
WHERE persID IN (select fatherID from person
WHERE fatherID IS NOT NULL)
但我一辈子都想不出如何将它们一起展示(同时相互关联)。我使用交叉连接吗?联合所有?
这只是一个连接,几次。与 couple
table:
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;