Jef
Jef

Reputation: 811

Mysql select max maximum sum values

I have a database which contains some picture data and a linking table. The tables are build-up like this:

---pictures---
picid    Lat  Lon
1        5    6
2        7    31
3        31   43
4        -3   35

---user2pictures---
picid   userid  vote
1       1      1
1       2      1
3       1     -1
3       2      1
4       2     -1

The table pictures contains a picture id and some data about the image, the table user2votes contains vote data from the images. Each user is able to vote on images, but they can only vote 1 time, so the vote will be either 1 (like) or -1 (dislike).

I want to select everything from the pictures table from pictures which have the highest number of votes. Pseudoquery which might explain better what I want: SELECT * FROM pictures WHERE (SELECT MAX(SUM(vote)) FROM user2pictures LIMIT 12

In this example picture 1 would return at the top, picture 3 would follow and picture 4 as the last one. I really don't know how to solve this, some help in the right direction would be very much appreciated!

Thanks!

Upvotes: 1

Views: 1145

Answers (3)

Barranka
Barranka

Reputation: 21047

I'll assume that you also want to show the pictures with no votes. So, you can try this:

select 
    p.picId, sum(v.vote) as votes
from 
    pictures as p
    left join user2pictures as v on p.picId = v.picId
group by
    p.picId
order by
    sum(v.vote) desc
limit 12;

The left join is what lets you show the pictures with no votes (the column votes will have the value 0)

Hope this helps

Upvotes: 2

echo_Me
echo_Me

Reputation: 37233

try this

   select p.`picid`, `Lat`, `Lon` from pictures p
   inner join user2pictures u2p
   on p.picid = u2p.picid
   group by u2p.picid
   order by sum(vote) desc
   limit 12

DEMO

Upvotes: 4

Ed Gibbs
Ed Gibbs

Reputation: 26343

The answer is to JOIN the tables, SUM the votes, and ORDER high-to-low by the sum of the votes

SELECT pictures.*, SUM(user2pictures.vote) AS VoteTotal
FROM pictures
JOIN user2pictures ON pictures.picid = user2pictures.picid
GROUP BY pictures.picid
ORDER BY VoteTotal DESC
LIMIT 12

Upvotes: 4

Related Questions