How to delete a range of records at once on MySQL?

前端 未结 4 433
野性不改
野性不改 2020-12-09 00:48

I have rows over 60000 in my table. How can I delete rows from 40000 to 50000 at once?

相关标签:
4条回答
  • 2020-12-09 01:27

    I'm assuming you want to do this based on the the default order of the table, and you don't have a natural key or some other way to order these in the table data.

    I.e. SELECT * FROM WORDS returns:

    Hi
    Hello
    Bye
    Goodbye
    What's up
    

    So if you said you wanted to delete rows 2 to 4, do you want to delete Hello, Bye, and Goodbye. Right?

    Is the return order of your table deterministic? In other words, to you get the results in the same order every time? Ideally, you would be able to identify a column in your table that contains data you could key off of, which would let you use Tricker's answer.

    If that isn't true, you will need to use the row number for your between statement. I'm not a mysql user, the code below would undoubtedly be cleaner if I were. Additionally, I don't even have a mysql database to test the query against. I put together a sql statement using this post as a reference for how to get a row num in mysql. With MySQL, how can I generate a column containing the record index in a table?

    My query assumes you have some kind of primary key on your table. If not, there is no way to guarantee that you wont delete extraneous rows, plus it's good table design.

    DELETE FROM YOUR_TABLE 
    WHERE primarykey = 
    (SELECT  primarykey FROM 
       (SELECT t.primarykey, 
               @curRow := @curRow + 1 AS row_number
       FROM    YOUR_TABLE t
       JOIN    (SELECT @curRow := 0) r) 
    WHERE row_number between 40000 and 50000);
    
    0 讨论(0)
  • 2020-12-09 01:29

    You can use the between function:

    delete from exampleTable where id between 40000 and 50000
    

    or:

    delete from exampleTable where id >= 40000 and id <= 50000
    

    pretty simple?

    0 讨论(0)
  • 2020-12-09 01:36

    If you dont have a primary key and want to delete by row count i.e row range, it can be done via mysql export import. Do a custom export - Specify the start row and count. In your case, you ll need two exports: one for rows 0 - 40k, second for 50-last. Then import those two files into the table. Note: If importing large files is a problem, I recommend BigDump. http://www.ozerov.de/bigdump/

    0 讨论(0)
  • 2020-12-09 01:40

    Table: grocery

    id  item  
    ----------            
    1   rice
    2   soap
    3   rice
    4   rice
    

    DELETE FROM 'grocery' WHERE item="rice" LIMIT 2;

    This is easier than all the other ideas. for this particular item , there are 2 records can be deleted.

    And the answer is,

    2 rows deleted.

    SELECT * FROM grocery;

    id  item    
    ----------         
    1   rice
    2   soap
    
    0 讨论(0)
提交回复
热议问题