mysql删除固定行数

1、示例表

user表

CREATE TABLE `user` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(255) NOT NULL COMMENT '姓名',
  `age` int(11) NOT NULL COMMENT '年龄',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4635506 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

 

2、删除方式

2.1 第一种方式(推荐)

DELETE u 
FROM
	USER u,
	( SELECT id FROM USER WHERE id >= 4635501 ORDER BY id DESC LIMIT 1 ) t 
WHERE
	u.id = t.id;

2.2 第二种方式

DELETE 
FROM
USER 
WHERE
	id IN ( SELECT t.id FROM ( SELECT id FROM USER WHERE id >= 4635501 LIMIT 1 ) AS t );

 

2.1的效率要高于2.2

你可能感兴趣的:(mysql)