人物(ID,姓名,性别,父亲ID,母亲ID,配偶ID); 这是我的数据库列。 例如,如果id = 5,我怎么能找到这个人的堂兄? 我只需要使用人表。表弟是指某人的母亲和父亲的兄弟姐妹的孩子。 我尝试使用嵌套查询,但查询太多,无法跟踪结果。
例如,该查询找到某人的兄弟姐妹
SELECT name
FROM person
WHERE motherid = (SELECT motherid
FROM person
WHERE id = x)
AND fatherid = (SELECT fatherid
FROM person
WHERE id = x)
EXCEPT
(SELECT name FROM person WHERE id = x);
答案 0 :(得分:0)
也许加入父母的父母,然后回到子女的孩子。
(未经注释的记事本涂鸦)
SELECT DISTINCT
kid.name as kid,
cousin.name as cousin
FROM person kid
LEFT JOIN person AS parent
ON parent.id IN (kid.fatherid, kid.motherid)
LEFT JOIN person AS grandparent
ON grandparent.id IN (parent.fatherid, parent.motherid)
LEFT JOIN person AS auntcle
ON grandparent.id IN (auntcle.fatherid, auntcle.motherid)
AND auntcle.id != parent.id
LEFT JOIN person AS cousin
ON auntcle.id IN (cousin.fatherid, cousin.motherid)
WHERE cousin.fatherid != kid.fatherid AND cousin.motherid != kid.motherid -- redneck check