我正在为我的客户端从遗留数据库中删除重复项,我发现了一个MySQL查询来做到这一点。我想创建一个Rake任务来运行生产服务器的查询。我该怎么做?
MySQL查询:
select * from community_event_users;
create table dups as
select distinct username, count(*)
from community_event_users group by username
having count(*) > 1;
delete community_event_users from community_event_users inner join dups
on community_event_users.username = dups.username;
insert into community_event_users select username from dups;
答案 0 :(得分:22)
如果您使用的是Rails并使用ActiveRecord,则只需使用:
ActiveRecord::Base.execute(my_sql)
ActiveRecord::Base.connection.execute(my_sql)
my_sql是你的SQL字符串。
答案 1 :(得分:0)
对于 Rails 5 及更高版本,您最好使用:
ApplicationRecord.connection.execute <<~END_OF_SQL
YOUR QUERY HERE
END_OF_SQL