0

我在数据库中有 3 个表dishesprice_deals并且give_away_deals

# == Schema Information
#
# Table name: dishes
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  created_at  :datetime
#  updated_at  :datetime

# Table name: price_deals
#
#  id              :integer         not null, primary key
#  name            :string(255)
#  dish_id         :integer
#  created_at      :datetime
#  updated_at      :datetime

# Table name: give_away_deals
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  dish_id     :integer
#  created_at  :datetime
#  updated_at  :datetime

我必须从表中获取idand 。id 不在和 id 不在没有重复 id 的地方。namedishesprice_dealsgive_away_deals

假设我在dishesid1 到 10 中有 10 条记录。

price_dealsdish_id2,4,5

give_away_deals表中dish_id1,3,6

预期结果:

然后,我必须从表中获取idandnamedishesid7,8,9,10

我试过这个查询,

Dish.all(:select => "id, name", :conditions => ["id not in (select dish_id from price_deals)", "id not in (select dish_id from give_away_deals)"])

但它只返回不在price_deals.

上述查询有什么问题以及如何获得预期结果?

这是我在 Rails 服务器中得到的 SQL 查询

SELECT id, name FROM "dishes" WHERE (id not in (select dish_id from price_deals))
4

2 回答 2

1

好的时间来一些更大的答案。

试试这个代码:

first = PriceDeal.select(:dish_id).map(&:dish_id)
second = GiveAwayDeal.select(:dish_id).map(&:dish_id)
Dish.select('id, name').where("id not IN(?)", (first + second).uniq)

我认为应该生成一个好的 SQL 查询

于 2012-04-28T14:19:02.210 回答
1

你可以试试这段代码

Dish.includes(:price_deal, :give_away_deal).where("price_deals.id is null and give_away_deals.id is null")

方法includeswhere与一个查询一起使用

SQL (0.5ms)  SELECT `dishes`.`id` AS t0_r0, `dishes`.`name` AS t0_r1, `dishes`.`created_at` AS t0_r2, `dishes`.`updated_at` AS t0_r3, `price_deals`.`id` AS t1_r0, `price_deals`.`dish_id` AS t1_r1, `price_deals`.`created_at` AS t1_r2, `price_deals`.`updated_at` AS t1_r3, `give_away_deals`.`id` AS t2_r0, `give_away_deals`.`dish_id` AS t2_r1, `give_away_deals`.`created_at` AS t2_r2, `give_away_deals`.`updated_at` AS t2_r3 FROM `dishes` LEFT OUTER JOIN `price_deals` ON `price_deals`.`dish_id` = `dishes`.`id` LEFT OUTER JOIN `give_away_deals` ON `give_away_deals`.`dish_id` = `dishes`.`id` WHERE (price_deals.id is null and give_away_deals.id is null)

我使用 Rails 3.2.1 和 ruby​​ 1.9.3

于 2012-04-28T14:39:08.023 回答