如何从rake任务运行MySQL查询?

Kat*_*lez 15 ruby mysql rake ruby-on-rails

我正在为我的客户端从遗留数据库中删除重复项,我发现了一个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;
Run Code Online (Sandbox Code Playgroud)

kai*_*ain 23

如果您使用的是Rails并使用ActiveRecord,您只需使用:

ActiveRecord::Base.execute(my_sql)

ActiveRecord::Base.connection.execute(my_sql)
Run Code Online (Sandbox Code Playgroud)

my_sql是你的SQL字符串.