mysql - 来自多个模型的包含、选择、排序、限制(单个查询)

标签 mysql ruby-on-rails postgresql activerecord ruby-on-rails-4

我需要创建一个包含下表数据的查询:

*Conversation:一种在用户之间对消息进行分组的模型

class Conversation < ActiveRecord::Base
  # Associations
  has_many :messages, dependent: :destroy
  has_many :conversation_participants
  has_many :users, :through => :conversation_participants
  ## Attributes title, created_at, updated_at
end

* ConversationParticipant:一个跟踪对话用户的模型

class ConversationParticipant < ActiveRecord::Base
  ## Associations
  belongs_to :conversation
  belongs_to :user
  ## Attributes conversation_id, user_id, seen, created_at, updated_at
end

* Message:一种跟踪内容和发件人的模型

class Message < ActiveRecord::Base
  belongs_to :conversation
  belongs_to :sender, :class_name => "User"
  ## Attributes sender_id, content, conversation_id, created_at, updated_at
end

*User:具有属性 name

的模型

如何在单个查询中获取以下内容?

  1. limit of (5) recent messages from Message of uniq Conversation
  2. where user_id = current_user.id from ConversationParticipant
  3. order seen = false, then updated_at DESC from ConversationParticipant
  4. includes Conversation
  5. includes (Message sender) => User
  6. includes the other participant from ConversationParticipant => User

注意:includesselect很重要,因为这个问题是为了减少查询次数.

最佳答案

这里是我如何包含所有需要的模型,这个查询被翻译成 5 个 sql 查询,因为预加载没有加入(在单独的查询中运行)。

Message.joins("LEFT JOIN messages AS m ON messages.id != m.id 
              AND m.conversation_id = messages.conversation_id 
              AND messages.created_at < m.created_at")
       .where('m.id IS NULL')
       .joins("INNER JOIN conversation_participants AS cp 
              ON cp.conversation_id = messages.conversation_id 
              AND cp.user_id = #{user_id}")
       .order("cp.seen, cp.updated_at DESC")
       .limit(5)
       .includes(:sender)
       .includes(conversation: [{conversation_participants: :user}])

关于mysql - 来自多个模型的包含、选择、排序、限制(单个查询),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26876234/

相关文章:

php - 对于在一个查询中表中具有相关行的每个客户端,删除除最后 10 行之外的所有行吗?

mysql - 使用 :has_many associations and multiple conditions 查找

ruby-on-rails - 为什么要使用 Mocha rails ?那个有什么用途

postgresql - 检查触发器是否存在

mysql - MySQL中索引多的缺点

php - 使用 PHP 和 MySQL 检查上传的图像

python - hstore或json数据的Django数字比较?

sql - 有效地更新非常大的 PostgreSQL 数据库表

php - 如何在 laravel eloquent 中正确使用或在哪里?

ruby-on-rails - 在 Tomcat 中运行 jRuby + Rails