MySql查找父母有多少孩子

时间:2013-09-27 14:11:10

标签: mysql sql

我正在尝试从下面的数据中找出父母有多少孩子。此处levellevel,父级是id所链接的row。我正在尝试输出数据,按级别和子项数排列。

我拼凑了下面的sql,但这并没有真正按照我想要的方式返回结果:

select id, level, count(parent) as p, country 
  from stats group by level order by level asc, p desc;

你能帮忙吗?

表格数据

"id"    "level" "parent"    "country"
"1"     "1"     "0"         "US"
"2"     "2"     "1"         "US"
"3"     "2"     "1"         "US"
"4"     "2"     "1"         "US"
"5"     "2"     "1"         "US"

"6"     "3"     "2"         "US"
"7"     "3"     "2"         "US"

"8"     "1"     "0"         "US"

"9"     "2"     "8"         "US"
"10"    "2"     "8"         "US"
"11"    "2"     "8"         "US"

"12"    "3"     "9"         "US"
"13"    "3"     "9"         "US"
"14"    "3"     "9"         "US"

"15"    "3"     "10"        "US"
"16"    "3"     "10"        "US"
"17"    "3"     "10"        "US"
"18"    "3"     "10"        "US"

所需输出

"id"    "type"  "country"   "Count"
"1"     "1"     "US"        "4"
"8"     "1"     "US"        "3"
"10"    "2"     "US"        "4"
"9"     "2"     "US"        "3"
"2"     "2"     "US"        "2"

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT s.id, s.level, s.country, x.cnt 
FROM stats s, 
(SELECT DISTINCT(parent), COUNT(*) AS cnt 
FROM stats GROUP BY parent) x 
WHERE s.id = x.parent ORDER BY s.parent;

这样,它首先被命令从层次结构中显示更高的值。

答案 1 :(得分:0)

获取由父母分组的计数并将其加入列表以获取其他详细信息:

select idt.id as id, idt.level as type, idt.country as country, idc.ct as Count
from stats idt
inner join
(
  select parent, count(id) as ct
  from stats
  group by parent
) idc
on idt.id=idc.parent
order by level asc

答案 2 :(得分:0)

可能是这样的 - 在SELECT部分​​中添加所需的列:

SELECT
  s.id,
  IF (p.number IS NULL,0,p.number) AS number
  FROM stats s
    LEFT JOIN
    (
      SELECT
        parent,
        COUNT(*) AS number
        FROM stats
        GROUP BY parent
        WHERE parent!=0
    ) p
    ON s.id=p.parent
  ORDER BY s.level ASC, p.number DESC