DISTINCT在两个字段MYSQL + rails

时间:2015-08-17 14:53:09

标签: mysql ruby-on-rails

我有一个模型消息,其中包括:title,:description,:sender_id,:receiver_id。所以消息模型的记录可能

  1. Message.first (id:1,title:“Sample1”,description:“Test1”,sender_id:1,receiver_id:2)

  2. Message.second (id:1,title:“Sample2”,description:“Test2”,sender_id:3,receiver_id:4)

  3. Message.second (id:1,title:“Sample3”,description:“Test2”,sender_id:3,receiver_id:4)

  4. 我想要一个查询,根据sender_id和receiver_id

    提供不同的记录

    在Postgres Message.select(“DISTINCT ON(sender_id,receiver_id)*”)工作

    但是MYSQL2给出错误请帮忙

    修改

    来自我的工作

    messages = [] 
    messages << Message.all.to_a.uniq{|m| m.sender_id} 
    messages << Message.all.to_a.uniq{|m| m.receiver_id} 
    @messages = messages.flatten.uniq
    

1 个答案:

答案 0 :(得分:0)

似乎GROUP BY应该做得很好:

Message.group(:sender_id, :receiver_id)