让2个MySQL表看起来像这样:
表父母
+-------+-----------+-----------+
| id | name | birthdate |
+-------+-----------+-----------+
| 1 | Mary | 1974-05-02|
| 2 | John | 1970-06-03|
| 4 | James | 1984-07-04|
表儿童
+-------+-----------+-----------+-----------+-----------+
| id | parent | name |birthdate | gender |
+-------+-----------+-----------+-----------+-----------+
| 1 | 1 | Sara |2013-10-22 | female |
| 2 | 1 | Jack |2014-05-02 | male |
| 3 | 1 | Jill |2015-06-07 | female |
| 4 | 2 | Sam |2015-06-07 | male |
| 5 | 2 | Fred |2015-06-07 | male |
| 6 | 3 | Julie |2015-06-07 | female |
| 7 | 4 | Megan |2015-06-07 | female |
如何检索有3个孩子的父母(数)?
+---------+
|TOTAL |
+---------+
| 1 |
答案 0 :(得分:3)
使用COUNT
和HAVING
:
SELECT p.id
FROM parents p
INNER JOIN children c
ON c.parent = p.id
GROUP BY p.id
HAVING COUNT(c.id) = 3
获取parent
的数量为children
:
SELECT COUNT(*)
FROM (
SELECT p.id
FROM parents p
INNER JOIN children c
ON c.parent = p.id
GROUP BY p.id
HAVING COUNT(c.id) = 3
) t
答案 1 :(得分:0)
请参阅以下方式:
SELECT COUNT(p.id) as TOTAL
FROM parents as p
INNER JOIN children as c
ON c.parent = p.id
GROUP BY p.id
HAVING COUNT(c.id) = 3