计算内部联接查询

时间:2017-04-03 16:24:47

标签: sql oracle

我有两张桌子,其中一张带有'Avatars',另一张带有'Children',子表带有父头像ID和子头像ID的值。我试图从桌子上得到一个有2个以上孩子的头像列表。

表:

CREATE TABLE avatars
    (avatarID NUMBER CONSTRAINT pk_avatars PRIMARY KEY,
    username VARCHAR2(20),
    gender CHAR(1),
    );

CREATE TABLE children
    (childID NUMBER CONSTRAINT pk_children PRIMARY KEY,
    childAvatarID NUMBER,
    parentAvatarID NUMBER,
    mainParent NUMBER(1,0)
    );

关系:

ALTER TABLE children
ADD FOREIGN KEY (parentAvatarID)
REFERENCES avatars(avatarID)
ON DELETE CASCADE;

ALTER TABLE children
ADD FOREIGN KEY (childAvatarID)
REFERENCES avatars(avatarID)
ON DELETE CASCADE;

我的查询:

SELECT count(children.avatarid), avatars.username
FROM avatars
INNER JOIN (
  SELECT *
  FROM avatars
  INNER JOIN children ON avatars.avatarID = children.childAvatarID
  WHERE avatars.gender = 'M'
) children ON avatars.avatarID = children.parentavatarID
WHERE avatars.gender = 'M'
GROUP By children.avatarid, avatars.username;

无论头像有多少孩子,它都会显示为count(children.avatarid)1。

3 个答案:

答案 0 :(得分:1)

您按children.avatarid, avatars.username进行分组,只需按avatars.username进行分组。

SELECT count(children.avatarid), avatars.username
FROM avatars
INNER JOIN (
  SELECT *
  FROM avatars
  INNER JOIN children ON avatars.avatarID = children.childAvatarID
  WHERE avatars.gender = 'M'
) children ON avatars.avatarID = children.parentavatarID
WHERE avatars.gender = 'M'
GROUP By avatars.username;

答案 1 :(得分:1)

  

拥有2个以上孩子的头像列表

试试这个:

select a.*,
    c.child_count
from avatars a
join (
    select parentAvatarId,
        count(*) as child_count
    from children c
    join avatars a on a.avatarId = c.childAvatarId
    where a.gender = 'M'
    group by parentAvatarId
    having count(*) > 2
    ) c on a.avatarId = c.parentAvatarId
where a.gender = 'M'

答案 2 :(得分:1)

select avatars.avatarID, count(children.childID) as numberOfChildren
from avatars 
join children on children.parentAvatarID = avatars.avatarID
group by children.parentAvatarID
having numberOfChildren >= 2;