MySQL查询帮助
鉴于以下两个表格:MySQL查询帮助,mysql,Mysql,鉴于以下两个表格: 用户(用户id、用户名、位置、, (电邮) 投票(用户id、值、日期、ip) 如何执行MySQL查询以返回所有用户的总投票数和每个用户的投票总数 多谢各位 select u.user_id, (select count(user_id) from votes v where v.user_id = u.user_id) as num_votes, (select sum(value)
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
这对我很有用:
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)
在这种情况下,“u.user\u id=v.user\u id上的左外部连接投票v”可以使用“自然左连接投票v”@Alex:或
使用user\u id将投票连接为v
。哪个不重要。