V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
WildCat
V2EX  ›  Ruby on Rails

站内信数据表,如何取出某个用户最近 10 个联系人?

  •  
  •   WildCat · 2014-10-23 21:46:02 +08:00 · 3520 次点击
    这是一个创建于 3465 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我的站内信的数据表大约有如下字段:

    • id
    • receiver_id
    • sender_id
    • is_read
    • content
    • created_at

    eg. 如何取出 receiver_id = 1 的最近10个 sender_id ?

    第 1 条附言  ·  2014-10-23 22:56:27 +08:00
    @xenme
    @yangqi
    表述有误,10个不同的sender_id
    7 条回复    2014-10-24 09:52:42 +08:00
    xenme
        1
    xenme  
       2014-10-23 21:50:57 +08:00
    不是特别熟悉,大概应该这样:
    select * from table where receiver_id=1 order by creted_at desc limit 10
    yangqi
        2
    yangqi  
       2014-10-23 21:51:20 +08:00
    SELECT sender_id FROM 表 WHERE receiver_id=1 ORDER BY created_at DESC LIMIT 10;
    xenme
        3
    xenme  
       2014-10-23 21:52:32 +08:00   ❤️ 1
    可能sender有重复
    select distinct sender_id,created_at from table where receiver_id=1 order by creted_at desc limit 10
    heaton_nobu
        4
    heaton_nobu  
       2014-10-23 21:59:45 +08:00
    我只想问问为什么不用主键id,而非要用created_at,难道不是新建的id就大吗
    WildCat
        5
    WildCat  
    OP
       2014-10-23 23:00:26 +08:00
    @xenme 感谢。已经找到:

    http://guides.rubyonrails.org/active_record_querying.html
    ```ruby
    query = Client.select(:name).distinct
    # => Returns unique names

    query.distinct(false)
    # => Returns all names, even if there are duplicates
    ```

    结贴。
    staticor
        6
    staticor  
       2014-10-23 23:10:45 +08:00
    用groupby 之类的对sender_id 去个重?
    msg7086
        7
    msg7086  
       2014-10-24 09:52:42 +08:00 via iPhone   ❤️ 1
    where.distinct.first 10
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3520 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 04:55 · PVG 12:55 · LAX 21:55 · JFK 00:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.