如何查询table1中的数据,其中table1_id不在table2中,table1_id不在表3中

时间:2012-04-28 13:04:40

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我在数据库dishesprice_dealsgive_away_deals

中有3个表
# == 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

我要从id表中获取namedishes。 id不在price_deals且ID不在give_away_deals且没有重复ID。

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

price_dealsdish_id2,4,5

give_away_dealsdish_id1,3,6

预期结果:

然后,我要从id表中获取namedishes id 7,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))

2 个答案:

答案 0 :(得分: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查询

答案 1 :(得分: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