Delete all rows except first N from a table having single column

后端 未结 3 994
醉梦人生
醉梦人生 2021-01-03 01:12

I need a single query. Delete all rows from the table except the top N rows. The table has only one column. Like,

|friends_name|
==============
         


        
3条回答
  •  梦谈多话
    2021-01-03 02:11

    If you don't have an id field, i suppose you use an alphabetic order.

    MYSQL

    DELETE FROM friends 
    WHERE friends_name 
    NOT IN (
        SELECT * FROM (
            SELECT friends_name 
            FROM friends 
            ORDER BY friends_name ASC
            LIMIT 10) r
    )
    

    You delete all rows exept the 10 firsts (alphabetic order)

提交回复
热议问题