我需要知道是否有可能通过out子查询来实现这一点。。
这是我的表格结构:
id-name-father_id
1 joe 0
2 mark 0
3 muller 0
4 miki 2
5 timi 2
6 moses 2
7 david 1
8 momo 0
9 daniel 0
10 ermi 3
我的表格逻辑是
0
意味着他不是某个的孩子1+
意味着他是那个排的人的儿子。
注意:如果有人有孩子,他仍然父亲id中将有0(这意味着我的表中没有祖父)
我的问题是:
SELECT id, name, count(id=father_id) as sons
WHERE father_id = 0
我想要的是非子级(father_id=0)
和sum
的列表孩子们。有没有一种方法可以在没有子查询的情况下获得结果?
应该这样做(MySQL):
SELECT `parents`.`id`, `parents`.`name`, COUNT(`children`.*) AS sons
FROM `people` AS parents
LEFT JOIN `people` AS children ON `parents`.`id` = `children`.`father_id`
WHERE `parents`.`father_id` = 0
GROUP BY `parents`.`id`
根据Gary,我们需要在其他SQL数据库中添加name
到GROUP BY
:
SELECT `parents`.`id`, `parents`.`name`, COUNT(`children`.*) AS sons
FROM `people` AS parents
LEFT JOIN `people` AS children ON `parents`.`id` = `children`.`father_id`
WHERE `parents`.`father_id` = 0
GROUP BY `parents`.`id`, `parents`.`name`
我们在这儿把桌子连在一起。所以我们和所有的父母一起带着他们的孩子。
这将导致这样的结果:
parents.id parents.name children.id children.name
1 joe 7 david
2 mark 4 miki
2 mark 5 timi
2 mark 6 moses
3 muller 10 ermi
8 momo - - # left join allows this line
9 daniel - -
但现在我们每个父母都有好几次了。因此,我们对父id进行分组,这将导致以下结果:
parents.id parents.name COUNT(children.*)
1 joe 1
2 mark 3
3 muller 1
8 momo 0
9 daniel 0
您应该能够在没有任何联接或子查询的情况下执行此操作,如下所示:
select case father_id when 0 then id else father_id end id,
max(case father_id when 0 then name end) name,
sum(sign(father_id)) sons
from table
group by case father_id when 0 then id else father_id