简体   繁体   English

PHP / MySQL 如何从一个表中获取值并检查另一个表

[英]PHP / MySQL How to get values from one table and check against another table

I'm creating a small voting application.我正在创建一个小型投票应用程序。 I need to get the images and their vote counts from one table, and then check another vote table to see if the user has already voted for each of these images already.我需要从一个表中获取图像及其投票计数,然后检查另一个投票表以查看用户是否已经为这些图像中的每一个投票。

To get the images from the image table I'm doing this:要从图像表中获取图像,我正在这样做:

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

But I also need to check in the "vote" table that their userid isn't already associated with the (image) id from this query.但我还需要在“投票”表中检查他们的用户 ID 尚未与此查询中的(图像)ID 相关联。 I only need to show 5 images at a time, hence the LIMIT applied to the first query.我一次只需要显示 5 张图像,因此 LIMIT 应用于第一个查询。

I'm not sure whether I need to do some joining or multiple queries.我不确定是否需要进行一些加入或多个查询。

my vote table has fields:我的投票表有字段:

  • id ID
  • voter_id选民ID
  • image_id image_id

EDIT: Thanks for all your feedback.编辑:感谢您的所有反馈。 Some more info:更多信息:

total_votes felt dirty when I put it in there, but I couldn't work out a better way to count up the votes each time.当我把 total_votes 放在那里时,感觉很脏,但我想不出更好的方法来计算每次的选票。 Wouldn't it be inefficient if every time there was a vote cast, or a request to view the leaderboard that all the votes had to be tallied and sorted?如果每次有投票,或者要求查看排行榜的时候,所有的投票都必须被统计和排序,那不是效率低下吗? Forgive me for my sins - I'm not a database programmer!原谅我的罪过——我不是数据库程序员!

Using LEFT JOIN/IS NULL:使用 LEFT JOIN/IS NULL:

   SELECT i.id, i.file_name, i.total_votes 
     FROM _images i
LEFT JOIN VOTES v ON v.image_id = i.id
                 AND v.voter_id = ?
    WHERE approved = 1 
 ORDER BY total_votes DESC 
    LIMIT ".($page*5).", 5"

Using NOT EXISTS使用NOT EXISTS

   SELECT i.id, i.file_name, i.total_votes 
     FROM _images i
    WHERE approved = 1 
      AND NOT EXISTS (SELECT NULL
                       FROM VOTES v
                      WHERE v.image_id = i.id
                        AND v.voter_id = ?)
 ORDER BY total_votes DESC 
    LIMIT ".($page*5).", 5

Using NOT IN使用NOT IN

  SELECT i.id, i.file_name, i.total_votes 
    FROM _images i
   WHERE approved = 1 
     AND i.id NOT IN (SELECT v.image_id
                      FROM VOTES v
                     WHERE v.voter_id = ?)
ORDER BY total_votes DESC 
   LIMIT ".($page*5).", 5

Suggested Reading:推荐阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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