mysql - 在rails中,如何查询连接表中的字段?

标签 mysql sql ruby-on-rails

在 Rails 中,我有两个模型::contest:problem。每个竞赛都有很多问题,一个问题可以属于多个竞赛。不同比赛中的一个问题,可能有不同的“索引”。

我使用模型 :contest_problem 来加入 :contest:problem。在 :contest_problem 中,我有一个字段 index,用于标记竞赛中问题的“索引”。

现在,当我执行 Contest.find(...).problems.find(...) (... 是我想要的 racing_id 或 Problem_id查询),rails 将创建一个 sql 查询:

SELECT `problems`.*
    FROM `problems`
    INNER JOIN `contest_problems` ON `problems`.`id` = `contest_problems`.`problem_id`
    WHERE `contest_problems`.`contest_id` = 1 AND `problems`.`id` = 1
    LIMIT 1

我想执行这个sql查询:

SELECT `problems`.*, `contest_problems`.`index`
    FROM `problems`
    INNER JOIN `contest_problems` ON `problems`.`id` = `contest_problems`.`problem_id`
    WHERE `contest_problems`.`contest_id` = 1 AND `problems`.`id` = 1
    LIMIT 1

我应该在 Rails 中做什么?

<小时/>

型号:

class Contest < ActiveRecord::Base
  has_many :contest_problems
  has_many :problems, through: :contest_problems
end

class Problem < ActiveRecord::Base
  has_many :contest_problems
  has_many :contests, through: :contest_problems
end

class ContestProblem < ActiveRecord::Base
  belongs_to :contest
  belongs_to :problem
end

迁移:

class CreateContestProblems < ActiveRecord::Migration
  def change
    create_table :contest_problems do |t|
      t.integer :contest_id
      t.integer :problem_id
      t.string  :index,     limit: 2

      t.timestamps
    end
  end
end

最佳答案

尝试这个查询:

Problem.includes(:contests, :contest_ problems)
  .where(@problem.id)
  .where(contests: { id: @contest.id } ).first

这将在一次数据库查询中为您提供所需的信息。

关于mysql - 在rails中,如何查询连接表中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27203346/

相关文章:

mysql - 一个 MySQL 查询可能吗? "column contains any of the array' 的值”

sql - 在mysql中按日期分组结果

sql - 在 Postgres 中创建触发器

ruby-on-rails - 邪恶的 PDF : How to remove top margin from COVER page?

ruby-on-rails - ActiveRecord/PostgreSQL 中具有指定重复周期 + 终止日期的重复记录

mysql - 如何从独立于数据库的应用程序调用存储过程 C#,codefirst

python - 使用torndb python进行日期时间格式化

jquery - Rails,单击时更改 HTML 元素的类属性

php - 无法使用 PhpMyAdmin 正确连接到外部服务器

sql - OR 条件使查询执行速度变慢