[英]how can I write a postgresql query to find someone's cousin in database?
人(ID,姓名,性别,父亲ID,母亲ID,配偶ID); 这是我的数据库列。 例如,如果 id = 5 我怎样才能找到这个人的堂兄弟? 我必须只使用 person 表。 表弟是指某人的母亲和父亲的兄弟姐妹的孩子。 我尝试使用嵌套查询,但结果查询太多了。
例如,该查询查找某人的兄弟姐妹
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);
也许加入父母的父母,然后回到他们孩子的孩子。
(未经测试的记事本涂鸦)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.