从具有单列的表中删除除前N之外的所有行

Naa*_*aaN 5 mysql

我需要一个查询.Delete除了前N行之外,表中的所有行.该表只有一列.喜欢,

|friends_name|
==============
| Arunji     |
| Roshit     |
| Misbahu    |
| etc...     |
Run Code Online (Sandbox Code Playgroud)

此列也可能包含重复的名称.

  • 包含重复的名称

  • 只有一列.

fth*_*lla 10

If you can order your records by friends_name, and if there are no duplicates, you could use this:

DELETE FROM names
WHERE
  friends_name NOT IN (
    SELECT * FROM (
      SELECT friends_name
      FROM names
      ORDER BY friends_name
      LIMIT 10) s
  )
Run Code Online (Sandbox Code Playgroud)

Please see fiddle here.

Or you can use this:

DELETE FROM names ORDER BY friends_name DESC
LIMIT total_records-10
Run Code Online (Sandbox Code Playgroud)

where total_records is (SELECT COUNT(*) FROM names), but you have to do this by code, you can't put a count in the LIMIT clause of your query.