[英]How do you run a MySQL query from a rake task?
I'm working on removing duplicates from a legacy database for a client of mine, and I've found a MySQL query to do just that.我正在为我的客户从遗留数据库中删除重复项,我发现了一个 MySQL 查询可以做到这一点。 I want to create a Rake task to run the query for the production server.我想创建一个 Rake 任务来运行生产服务器的查询。 How would I do that?我该怎么做?
MySQL query: 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;
If you are on Rails and using ActiveRecord you can simply use:如果您在 Rails 上并使用 ActiveRecord 您可以简单地使用:
ActiveRecord::Base.execute(my_sql)
ActiveRecord::Base.connection.execute(my_sql)
Where my_sql is your SQL string.其中 my_sql 是您的 SQL 字符串。
For Rails 5 and above you better use:对于 Rails 5 及更高版本,您最好使用:
ApplicationRecord.connection.execute <<~END_OF_SQL
YOUR QUERY HERE
END_OF_SQL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.