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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度