我有一个在 2 个表上运行的 sql:
affiliates_comisions.each do |aff|
connection.update("
UPDATE comissions AS coms,
conversions AS conve
SET conve.active=0
WHERE coms.conversion_type_id=conve.conversion_type_id
AND conve.user_id="+aff.id.to_s+"
AND conve.active=1
AND coms.method = 'one_time'")
end
我的问题是,如果有的话,我怎么能以更好的方式做到这一点?我找不到更新需要另一个表中的条件为真的字段的方法...
如果您需要其他详细信息,请告诉我。
更新 1
该affiliates_commissions 是:
total_pay_sql = "(SELECT SUM(payment)
FROM comissions AS coms,conversions AS conve
WHERE coms.conversion_type_id=conve.conversion_type_id
AND conve.user_id=usr.id
AND conve.active=1)"
affiliates_comisions = self.
select('*,'+total_pay_sql+' AS total_pay').
from("users AS usr").
where(total_pay_sql+">=5")
更新 2
以下是模型:
class Comission < ActiveRecord::Base
belongs_to :conversion_type
attr_accessible :method, :payment
validates_inclusion_of :method, :in => [:recurring, :one_time]
...
class Conversion < ActiveRecord::Base
attr_accessible :conversion_type_id, :restaurant_id, :user_id, :active
belongs_to :user
belongs_to :restaurant
belongs_to :conversion_type
...
class ConversionType < ActiveRecord::Base
attr_accessible :name
has_many :conversions
end
更新 3
在@RGB 提出建议后,我进行了一些更改并添加了:
#To conversion model#
has_many :comissions, :through => :conversion_type
#To comission model#
has_many :conversions, :through => :conversion_type
#To conversion_type model#
has_many :conversions
has_many :comissions
现在我设法让选择工作更艰难,这件事运行 2 个查询,我不确定这比我编写一个查询来进行更新更好,但也许你可以帮助我。所以这是我设法编写的选择以获得我需要的转换。
@conversions = Comission.find_by_method('one_time').conversions.find_all_by_active_and_user_id(1,affiliates_comisions.collect(&:id))
现在的问题是我无法对此运行更新,或者我如何在不运行此选择的情况下进行更新查询?...
回答
我终于设法让事情按我的意愿工作。这是我经过一些更改后的内容:
total_pay_sql = "(SELECT SUM(payment)
FROM comissions AS coms,conversions AS conve
WHERE coms.conversion_type_id=conve.conversion_type_id
AND conve.user_id=usr.id
AND conve.active=1)"
affiliates_comisions = self.
select('*,'+total_pay_sql+' AS total_pay').
from("users AS usr").
where(total_pay_sql+">=?",@@minimum_pay)
#we run a normal update here to set the one time conversions to active=0 so we only pay for them once
@conversions = Comission.where({:method=>'one_time'}).joins(:conversions).where("active=1 AND user_id IN(?)",affiliates_comisions.collect(&:id)).update_all(:active=>0)
最后一行是我想要的答案,并结合@RGB 所说的我已经设法使它工作。这是最后一行执行的查询:
UPDATE `comissions` INNER JOIN `conversion_types` ON `conversion_types`.`id` = `comissions`.`conversion_type_id` INNER JOIN `conversions` ON `conversions`.`conversion_type_id` = `conversion_types`.`id` SET `active` = 0 WHERE `comissions`.`method` = 'one_time' AND (active=1 AND user_id IN(41))
完美的!!!:DI 希望它对其他人也有帮助!
谢谢。