Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I want to create a Rake task to run the query for the production server. How would I do that?

MySQL query:

    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;
like image 515
Kathryn Gonzalez Avatar asked Jul 18 '11 16:07

Kathryn Gonzalez


People also ask

How do I run a MySQL query?

You can execute a MySQL query towards a given database by opening the database with phpMyAdmin and then clicking on the SQL tab. A new page will load, where you can provide the desired query. When ready click on Go to perform the execution. The page will refresh and you will see the results from the query you provided.

How do I run a SQL query in MySQL workbench?

To do that, first select the desired database from the left column menu by double-clicking it. Then type in the MySQL query you want to run in the text field in the middle of the program window and use the yellow lightning button above that text field to run the query.


1 Answers

If you are on Rails and using ActiveRecord you can simply use:

ActiveRecord::Base.execute(my_sql)

ActiveRecord::Base.connection.execute(my_sql)

Where my_sql is your SQL string.

like image 148
kain Avatar answered Oct 06 '22 00:10

kain