2

Given the following two tables:

  1. users (user_id, username, location, email)
  2. votes (user_id, value, date, ip)

How can I perform a MySQL query to return all the users with total number of votes and sum of votes for each user?

Thank you.

2 Answers 2

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 ...

EDIT: The subselects are not the most elegant solution, and not really necessary. So here's an outer join version:

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
Sign up to request clarification or add additional context in comments.

2 Comments

In this case, instead "left outer join votes v on u.user_id = v.user_id" can use "natural left join votes v"
@Alex: Or JOIN votes AS v USING user_id. It doesn't much matter which.
0

This works for me:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.