开发者

PHP / MySQL Checking data between tables with long query

开发者 https://www.devze.com 2023-03-11 05:57 出处:网络
This is a more detailed question as my previous attempt wasn\'t clea开发者_运维问答r enough. I\'m new to MySQL and have no idea about the best way to do certain things. I\'m building a voting applicat

This is a more detailed question as my previous attempt wasn't clea开发者_运维问答r enough. I'm new to MySQL and have no idea about the best way to do certain things. I'm building a voting application for images and am having trouble with some of the finer points of MySQL

My db

_votes

  • id
  • voter_id
  • image_id

_images

  • id
  • file_name
  • entrant_id
  • approved

_users

  • id
  • ...

Basically I need to do the following:

  1. tally up all votes that are approved
  2. return the top 5 with the most votes
  3. check if the user has voted on each of these 5 (return Boolean) from another table

I've tried variations of

SELECT i.id, i.file_name, i.total_votes
FROM _images i WHERE i.approved = 1 
CASE WHEN (SELECT count(*) from _votes v WHERE v.image_id = i.id AND v.voter_id = ?) > 0 THEN '1' ELSE '0' END 'hasvoted'
ORDER BY i.total_votes DESC LIMIT ".($page*5).", 5

is that something I should try and do all in one query?

This query was working fine before I tried to add in the 'hasvoted' boolean:

SELECT id, file_name, total_votes FROM _images WHERE approved = 1 ORDER BY total_votes DESC LIMIT ".($page*5).", 5

At the moment I'm also storing the vote count in the _images table and I know this is wrong, but I have no idea about how to tally the votes by image_id and then order them.


Let me give this a shot to see if I understand your question:

SELECT i.*,(SELECT COUNT(*) FROM _votes WHERE i.id = image_id) AS total_votes, (SELECT count(*) from _votes where i.id = image_id and user_id = ?) as voted  FROM _images AS i WHERE i.approved = 1
0

精彩评论

暂无评论...
验证码 换一张
取 消