sql - 如何编写 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);
解决方案
也许加入父母的父母,然后回到他们孩子的孩子。
(未经测试的记事本涂鸦)
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
推荐阅读
- docker - 如何在 nginx alpine docker 映像中启用本机模块
- java - 没有 android.inputmethodservice.Keyboard 的自定义键盘
- python - 制作自定义(tf.function)函数二维数组
- r - 如何在 R 的数据框中显示大数字?
- debugging - 使用 PIC16F1829 间接寻址时如何正确清除 RAM
- javascript - React 中的空状态,异步函数的调用
- c# - EF Core - 如果为 Null,则选择父值
- adfs - adfs 设置中的 itfoxtec-identity-saml2 颁发者是什么?
- kubernetes - jhipster kubernetes 部署没有redis
- javascript - 单击Jquery中的弹出按钮后如何显示刻度线?