鉴于以下两个表:
如何执行MySQL查询以返回所有用户的总票数和每个用户的投票总数?
谢谢。
答案 0 :(得分:3)
select u.user_id,
(select count(user_id)
from votes v
where v.user_id = u.user_id) as num_votes,
(select sum(value)
from votes v
where v.user_id = u.user_id) as sum_votes
from users u
# if you want: order by ...
编辑:子选择不是最优雅的解决方案,并非真正必要。所以这是一个外连接版本:
select u.user_id, count(v.user_id) as num_votes, sum(v.value) as sum_votes
from users u
left outer join votes v
on u.user_id = v.user_id
group by u.user_id
答案 1 :(得分:0)
这对我有用:
create table user
(
id int not null auto_increment,
name varchar(80) not null,
location varchar(80) default '',
email varchar(80) default '',
primary key(id)
);
create table vote
(
id int not null auto_increment,
count int not null,
election_date date,
user_id int,
primary key(id),
foreign key(user_id) references user(id)
);
select
user.name, user.email, sum(vote.count)
from user
left join
vote
on user.id = vote.user_id
group by (user_id)