如何从Oracle中的另一个表获取一个表的ID计数

时间:2019-06-15 06:58:39

标签: sql oracle

我正在尝试在Voting上创建一个数据库项目,其中有一个候选表和一个cast_vote表。 can_id是候选表的pk和cast_vote表的fk。我想知道can_id在cast_vote中插入了多少次,然后我可以显示候选人的姓名和总投票。

我希望输出如下: 名称Aff_party Total_vote(cast_vote)

 select candidate.name
  2  count(cast_vote.can_id) as t_v
  3  from candidate
  4  left join cast_vote on candidate.can_id=cast_vote.can_id
  5  ;

create table voter(
    voter_id number(8),
    full_name varchar(20),
    gender varchar(7),
    seat_no number(5),
    age number(3) check (age>=18),
    primary key (voter_id)
);

create table candidate(
    can_id number(8),
    name varchar(256),
    age number(3) check (age>=18),
    gender varchar(7),
    aff_party varchar(256),
    seat_no number(5),
    seat_name varchar(256),
    net_income number(8),
    primary key(can_id)
);

create table cast_vote(
    vote_no number(15) not null,
    voter_id number(8) not null unique,
    can_id number(8),
    primary key(vote_no),
    foreign key (voter_id) references voter(voter_id),
    foreign key(can_id) references candidate(can_id)
);

2 个答案:

答案 0 :(得分:0)

您只是缺少GROUP BY子句。考虑到多个候选名称可以相同,您需要在group by子句中同时添加can_id和候选人名称。

尝试一下-

SELECT C.can_id,
C.name,
COUNT(CV.can_id) AS t_v
FROM candidate C
LEFT JOIN cast_vote CV on C.can_id=CV.can_id
GROUP BY C.can_id,C.name

答案 1 :(得分:0)

您需要一个GROUP BY。假设您没有重复的候选人姓名:

SELECT c.name, c.aff_party, COUNT(cv.can_id) as t_v
FROM candidate c LEFT JOIN
     cast_vote cv
     ON c.can_id = cv.can_id
GROUP BY c.name, c.aff_party;

如果您可以有重复的候选人姓名,那么您将希望通过其ID来区分他们:

SELECT c.can_id, c.name, c.aff_party,
       COUNT(cv.can_id) as t_v
FROM candidate c LEFT JOIN
     cast_vote cv
     ON c.can_id = cv.can_id
GROUP BY c.can_id, c.name, c.aff_party;

请注意,SELECT中每个未聚合的列也在GROUP BY中。