简体   繁体   English

MySQL:显示一个用户未投票的随机结果

[英]MySQL: Display one random result which a user has not voted on

I need help on displaying one random result in which the current user has not voted on. 我需要帮助显示当前用户尚未投票的随机结果。

Currently my database setup and the last query I have tried can be found on http://sqlfiddle.com/#!2/2f91b/1 目前我的数据库设置和我尝试的最后一个查询可以在http://sqlfiddle.com/#!2/2f91b/1找到

Basically I can isolate each individual item using this query: 基本上我可以使用此查询隔离每个单独的项目:

SELECT a.img_url, a.item_id, a.user_id, a.img_status, b.item_question, c.user_name, c.user_fbid, d.voter_id, count(d.img_id) AS totalVotes
FROM os_photos a 
LEFT JOIN os_items b ON a.item_id = b.item_id
LEFT JOIN os_users c ON a.user_id = c.user_id
LEFT JOIN os_votes d ON a.img_id = d.img_id
GROUP BY a.img_id
ORDER BY RAND()
LIMIT 1

My Problem is: With the SQL knowledge that I have, I am unable to isolate the results to show only the rows in which user #2 has not voted on. 我的问题是:凭借我拥有的SQL知识,我无法隔离结果以仅显示用户#2未投票的行。 I realize the problem is when I use group by, it combines the voter_id and therefore I am unable to check if user #2 has had any input for the item. 我意识到问题是当我使用group by时,它结合了voter_id,因此我无法检查用户#2是否有任何项目输入。

Example: 例:

Item #  |  voter_id
1       |      2
1       |      3
2       |      2
3       |      1
3       |      4
4       |      3
4       |      1
5       |      1
5       |      2

With the above sample set, the resulting item should be either item #3, #4 or any other items which have not been voted on. 使用上面的样本集,结果项应该是项目#3,#4或任何其他尚未投票的项目。

Your help, advise and knowledge is greatly appreciated. 非常感谢您的帮助,建议和知识。

To get the items that dont exist you need a LEFT JOIN with condition that would otherwise make a positive match, and then add a WHERE clause matching one of the resulting columns to NULL : 要获取不存在的项,您需要LEFT JOIN ,条件否则会产生正匹配,然后添加一个WHERE子句,将其中一个结果列与NULL匹配:

SELECT a.img_url, a.item_id, a.user_id, a.img_status, b.item_question, c.user_name,c.user_fbid, d.voter_id, count(d.img_id) AS totalVotes
FROM os_photos a 
LEFT JOIN os_items b ON a.item_id = b.item_id
LEFT JOIN os_users c ON a.user_id = c.user_id
LEFT JOIN os_votes d ON a.img_id = d.img_id
LEFT JOIN os_votes d2 ON a.img_id = d2.img_id AND d2.voter_id=2
WHERE d2.voter_id IS NULL
GROUP BY a.img_id
ORDER BY RAND()
LIMIT 1

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

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