1

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!

3 Answers 3

4

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

Comments

4

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

1 Comment

Thanks for your input! Also thanks for the demo, I didn't know such thing existed, very useful for testing.
2

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

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.