首页 > 解决方案 > 如何编写 postgresql 查询以在数据库中查找某人的表弟?

问题描述

人(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);

标签: sqlpostgresql

解决方案


也许加入父母的父母,然后回到他们孩子的孩子。

(未经测试的记事本涂鸦)

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

推荐阅读