如何找到具有相同属性的sql记录?

时间:2013-12-29 00:32:45

标签: sql sqlite

我有一个名为parents的表格:

________________________________
|childID | motherID | fatherID |
--------------------------------
|   2    |     1    |    100   |
|   3    |     2    |    101   |
|   4    |     2    |    101   |
...

我需要与所有拥有相同父母的孩子的childID一起返回一张桌子。

我试过

SELECT childID
FROM parents
GROUP BY motherID, fatherID

但这也给了我没有兄弟姐妹的孩子。

1 个答案:

答案 0 :(得分:2)

SELECT
    ChildId 
FROM
    parents p
    JOIN
    (
        SELECT
            motherID,
            fatherID,
            COUNT(*)
        FROM
            parents
        GROUP BY
            motherID,
            fatherID
        HAVING
            COUNT(*) > 1
    ) motherFatherCount
    ON p.MotherId = motherFatherCount.MotherID AND
       p.FatherId = motherFatherCount.FatherId