用于从多个表中获取信息的SQL查询

时间:2015-11-05 10:09:58

标签: sql

好的,我是SQL的绝对初学者,我有一个任务要解决,而且我被困住了,所以我需要帮助你的想法如何获得所需的结果。

我有2个表 - 第一个是PARENTS,包含以下数据:

ID         Name          Age
1          John          25
2          Peter         28
3          Anny          30
4          Jack          32

,第二个表格为CHILDRENS,其中包含以下数据:

children_id           parent_id        name         age
1                        1             mary          5
2                        1             Susanne       4
3                        2             stephen       12
4                        4             Kevin         7

可以使用什么SQL命令获得以下结果:

id               parent name          number of childrens
1                  John                      2
2                  Peter                     1
3                  Anny                      0
4                  Jack                      1

提前致谢!

4 个答案:

答案 0 :(得分:1)

试试这个

select PARENTS.id,PARENTS.name,count(CHILDRENS.name)
from PARENTS left join CHILDRENS on PARENTS.id=CHILDRENS.parent_id
group by PARENTS.id,PARENTS.name

答案 1 :(得分:0)

正如Jarlh在评论中所提到的,请使用LEFT OUTER JOIN + Group by

SELECT p.id,
       p.name,
       Count(parent_id) as number_of_childrens
FROM   PARENTS p
       LEFT OUTER JOIN CHILDRENS c
                    ON c.parent_id = p.ID 
Group by p.id,
         p.name

答案 2 :(得分:0)

okBtnActionPerformed(java.awt.event.ActionEvent evt)

答案 3 :(得分:0)

SELECT A.ID
    , A.name AS parent_name
    , COUNT(B.children_id) AS number_of_children
FROM PARENTS AS A
LEFT JOIN CHILDRENS AS B
ON A.ID = B.parent_id
GROUP BY A.ID
    , A.name

左连接,计数和分组。