计算this.row与另一个表中的行相关的总行数

时间:2019-03-27 22:18:52

标签: sql postgresql

我有两个简单的表parentschildren。我正在计算至少有一个孩子的父母人数。

create table People(
    id integer unique,
    name varchar(120),
    primary key (id)
);

create table children(
    id integer unique,
    name varchar(120),
    parentId integer,
    primary key(id),
    foreign key (parentId) references People(id)
);

这是我尝试过的代码,但是却给了我孩子的总数:

select count(*)
from (people p join children ch on ch.parentid = p.id)
having count(ch.id) > 0; 

6 个答案:

答案 0 :(得分:1)

您已经关闭。您只需要针对每位父母进行子女检查:

SELECT COUNT(*) AS parents_with_children
FROM (SELECT p.name, COUNT(c.id) AS num_children
      FROM people p
      JOIN children c ON c.parentid = p.id
      GROUP BY p.name
      HAVING COUNT(c.id) > 0) p

Demo on dbfiddle

答案 1 :(得分:1)

  

我正在计算至少有一个孩子的父母人数。

这应该很简单:

SELECT COUNT(*) 
FROM people p
WHERE EXISTS (SELECT 1 FROM children c WHERE c.parentid = p.id)

使用EXISTS通常是检查某物是否存在的最有效方法。

答案 2 :(得分:0)

select count(p.*)
from people p inner join children ch
     on ch.parentid = p.id 

答案 3 :(得分:0)

具有EXISTS:

select count(distinct p.id) counter from people p
where exists (
  select 1 from children
  where parentid = p.id
)

甚至更好

select count(distinct parentid) counter 
from children 

因为您需要的所有信息都在表children中,所以只需计算列distinct中的parentid

答案 4 :(得分:0)

SELECT COUNT(*),p.*
FROM People p JOIN children c ON c.parnetId=p.id
WHERE NOT c.parnetId IS NULL 
GROUP BY (p.id)

(无需拥有,因为它无论如何只能加入现有的孩子)

答案 5 :(得分:0)

您可以尝试这样的事情,

SELECT COUNT(DISTINCT children.parentid)
FROM People 
INNER JOIN children 
ON children.parentid = people.id;