我在数据库dishes
,price_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
我要从id
表中获取name
和dishes
。 id不在price_deals
且ID不在give_away_deals
且没有重复ID。
假设我在dishes
表id
1到10中有10条记录。
在price_deals
表dish_id
中2,4,5
。
在give_away_deals
表dish_id
中1,3,6
然后,我要从id
表中获取name
和dishes
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))
答案 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")
方法includes
和where
与一个查询一起使用
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