简体   繁体   中英

Math between two tables with MySQL and PHP

I have two tables in my SQL database, one for the photos that users sent and another one for the votes which photo had on my application. I need to extract the 30 photos from the 'photos' table which had the most votes on the 'votes' table.

Is there a way to do it within a single query?

You should be able to use a query like this:

select
    a.photoFileName
from
    photos a
        join votes b
            on a.photoId=b.photoId
order by 
    b.voteCount desc
limit 30

Adjust the keys to your exact column names on the linked fields.

This assumes that the votes table has an number column (voteCount) that has a tally of the votes for that image.

Something like this ( if each vote is stored single ), but make your own adjustments:

SELECT
  p.id,
  COUNT( v.id )
FROM
  photos p
JOIN
  votes v ON p.id = v.photo_id
ORDER BY
  COUNT( v.id ) DESC
GROUP BY
  v.photo_id
LIMIT 30;

PS: I did not test the query, just gave you an example!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM