大家好我想要一个sql来删除数据库中最老的一行,目前我有这个:
DELETE FROM `videos` WHERE date_added IS NOT NULL LIMIT 1
这只会从我的数据库顶部删除还是会随机选择?
答案 0 :(得分:2)
您可以使用order by
并尝试这样 -
DELETE FROM `videos` WHERE date_added IS NOT NULL order by date_added desc LIMIT 1
了解更多信息:http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html
答案 1 :(得分:2)
您需要按日期,降序排序,因此第一个结果是最旧的结果,然后删除第一个结果。
DELETE FROM `videos`
WHERE data_added IS NOT NULL
ORDER BY date_added DESC
LIMIT 1;
只要您的date_added
列是MySQL日期类型或数字类型(例如Unix时间戳),此解决方案就会起作用。如果没有,您应该转换数据或修改数据库的结构(我建议稍后)。
为了投射数据,你可以这样做:
DELETE FROM `videos`
WHERE data_added IS NOT NULL
ORDER BY Cast(date_added as date) DESC
LIMIT 1;
答案 2 :(得分:0)
DELETE FROM `videos` order by date_added desc LIMIT 1
如果你只需要删除最旧的记录使用上面的查询,否则需要检查一些条件使用这一个
DELETE FROM `videos` WHERE date_added IS NOT NULL order by date_added desc LIMIT 1
答案 3 :(得分:0)
一种方法是,您可以匹配最小日期值,然后可以删除记录。
DELETE FROM `videos` WHERE date_added = (SELECT min(date_added) from videos) AND date_added IS NOT NULL LIMIT 1
第二种方式,您可以使用order by子句删除。
DELETE FROM `videos` WHERE date_added IS NOT NULL ORDER BY date_added ASC LIMIT 1
答案 4 :(得分:0)
试试这个
DELETE FROM `videos` order by date_added DESC LIMIT 1
答案 5 :(得分:0)
你也可以按id删除记录(如果它是自动递增的)
DELETE FROM `videos` order by id DESC LIMIT 1
这将删除最后一条记录