查询以查找与多个人有过孩子的所有人

5rgfhyps  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(269)

我需要找到所有和不止一个人有过孩子的人的名单。我正在使用一个表,其中包含人名personid。这个人的id还用作他们的母亲id和父亲id。

ID  NAME    Father ID   Mother ID
1   Paul        
2   Debbie      
3   Jessie      
4   Pam         1          3
5   Sue         1          3
6   Trish       1          3 
7   Sarah       1          2
9   John        
10  johnny      9          4
11  Ben         9          4

在上面的例子中,我想找到保罗,他有四个孩子和两个不同的人,黛比和杰西。

qoefvg9y

qoefvg9y1#

试试这个:

select * from 
your_table a where
(select count(distinct father_id, mother_id)
from your_table b where b.father_id=a.id or b.mother_id=a.id)>1;

看看它在sqlfiddle上运行。

lnvxswe2

lnvxswe22#

你可以用 COUNT(DISTINCT col) > 1 :

SELECT *
FROM table
WHERE Id IN (
    SELECT Father_Id
    FROM table
    GROUP BY Father_Id
    HAVING COUNT(DISTINCT Mother_id) > 1
    UNION ALL
    SELECT Mother_Id
    FROM table
    GROUP BY Mother_Id
    HAVING COUNT(DISTINCT Father_Id) > 1
    );

dbfiddle演示

相关问题