获得超过2个孩子的父母

时间:2015-08-18 04:25:55

标签: mysql sql

表格结构:

| id | parent |
   1     0
   2     1
   3     1
   4     2
   5     2
   6     2

如何获取具有2个以上子级的父行的id? (在上面的例子中应该只返回 id = 2 行)

2 个答案:

答案 0 :(得分:2)

尝试此查询

SELECT *
FROM tablename 
WHERE id IN
(
    SELECT parent
    FROM tablename
    GROUP BY parent
    HAVING COUNT(parent) > 2
)

答案 1 :(得分:1)

我相信这足以找到父ID

SELECT parent
FROM   tablename
GROUP  BY parent
HAVING Count(parent) > 2