I'm trying to make a high score list in a MySQL database, just 3 columns: id, name, and score. The table is called Highscores. I tried using this code:

DELETE FROM Highscores WHERE
Score = (SELECT min(Score) FROM Highscores)
AND (SELECT count(*) FROM Highscores) > 10;

But it gives this error:

#1093 - You can't specify target table 'Highscores' for update in FROM clause

How can I delete the row with the lowest value, only if there are more than 10 rows? There could possibly be more than one row with the lowest value, but I only want one to be deleted.

有帮助吗?

解决方案

delete from highscores where id = (select * from (
select id from highscores order by score desc limit 10,1) as t)

Another approach to keep only 10 greatest scores

delete from highscores where id in (select * from (
select id from highscores order by score desc limit 10,18446744073709551615) as t)

其他提示

I wonder if you could just create a view with high scores.

Try creating a temporary table and use that in your SELECT calls.

Use a stored procedure:

This runs only once

DELIMITER $$

DROP PROCEDURE IF EXISTS `Sanitize_Highscores`$$
CREATE PROCEDURE `Sanitize_Highscores`() READS SQL DATA
BEGIN
  DECLARE numrows int DEFAULT 0;
  SELECT COUNT(*) INTO numrows FROM Highscores;
  if numrows>10 THEN
    DELETE FROM Highscores ORDER BY Score LIMIT 1;
  END IF;
END$$

DELIMITER ;

and this replaces your query

CALL Sanitize_Highscores
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top