douniewei6346 2012-11-17 23:47
浏览 17
已采纳

选择用户之前没有见过的帖子

I am looking for the most efficient way to create the following functionality. A user will load a page, which will give them a random post (from the user_post table), but must exclude posts that they have previously viewed. My data structure is (simplified):

user_post
---------
id (PK)


user_post_view
--------------
id (PK)
user_id
user_post_id

Where user_post is a stored post, and user_post_view is relates a user to a post that they have viewed. So, in English the query would be:

Select a random post from the user_post table that there is no user_post_view record for

I am using the Yii framework, but even a "normal" SQL statement will help.

  • 写回答

2条回答 默认 最新

  • douwei2966 2012-11-17 23:56
    关注
    SELECT * FROM user_post p where 
    your_user_id NOT IN (SELECT user_id FROM user_post_view WHERE user_post_id = p.id)
    

    EDIT:

    EXISTS actually probably makes more sense here...and I tacked on your LIMIT 1 in case you just wanted 1 post

    SELECT * FROM user_post p where 
    NOT EXISTS (SELECT user_id FROM user_post_view WHERE user_post_id = p.id AND 
    user_id = your_user_id) LIMIT 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?