我有一个表,在结构示例中只有3个级别:
1他的儿子2岁2有一个儿子4岁6岁
3是父亲,他的儿子5岁
我还有一个儿子7岁
4没有儿子,因为这是结构的规则。
我的桌子是这个:
|Id_Father|nbsp nbsp|Id_Son |
nbsp nbsp 1 nbsp nbsp nbsp;2
nbsp nbsp 2 nbsp nbsp nbsp;4
nbsp nbsp 3 nbsp nbsp nbsp;5
nbsp nbsp 2 nbsp nbsp nbsp;6
nbsp nbsp 1 nbsp nbsp nbsp;7
只有我想提出我的问题,每个父亲都有一个儿子,这是我的问题的一部分:
SELECT R.* FROM getName R where not EXISTS (SELECT 1 from Estructura R2 where R.id = R2.Id_Son) And Exists (SELECT 1 from Estructura R2 where R.id = R2.Id_Father and not exists (SELECT 1 from Estructura R3 where R2.Id_Son = R3.Id_Father ))
我的查询得到了这个:
1和3,但我只想得到3。
试试这个:
select id_father
from Estructura
group by id_father
having count(distinct id_son) = 1