我正在尝试允许我的Rails应用程序创建关系的一些高级功能。我正在运行MySQL作为后端。下面的查询在PHPMyAdmin中运行得很好,但是在rails中尝试执行时,它什么都不做,没有错误,也没有数据库写入....
我使用活动记录来创建Campaign和Location之间的关系,然后下面的查询应该可以在campaign_metros表中构建:
class CampaignLocation < ActiveRecord::Base
belongs_to :campaign
belongs_to :location
after_touch :create_campaign_metro
private
def create_campaign_metro
@sql_insert="INSERT INTO `campaign_metros` (`campaign_id`,`metro_id`, `created_at`,`updated_at`)
SELECT f.`campaign_id`, f.`city_id`, NOW(), NOW()
FROM (SELECT d.`campaign_id`, d.`city_id`
FROM (SELECT c.`campaign_id`, c.`city_id`
FROM (SELECT distinct a.`campaign_id`, b.`city_id`
FROM `campaign_locations` a
INNER JOIN `locations` b
ON a.`location_id` = b.`id`) c) d
LEFT JOIN `campaign_metros` e
ON e.`campaign_id` = d.`campaign_id` and
e.`metro_id` = d.`city_id`
WHERE e.`metro_id` is null and e.`campaign_id` is null) f;"
ActiveRecord::Base.connection.execute(@sql_insert)
end
end
我从MySQL DELETE FROM with subquery as condition知道,在CodeReaper的第二个答案中,MySQL在处理子查询时需要另一级别的别名,但在Rails中运行我的查询什么都不做。
我怎样才能让它发挥作用?