检查行数并删除超出限制的最后一行

时间:2014-02-08 18:05:37

标签: mysql sql

目前我正在使用以下解决方案来检查记录数,然后删除超出限制的最后一个记录。伪代码:

var count = SELECT COUNT(*) AS count FROM table WHERE user_id = ?;

if (count > LIMIT) { // e.g [LIMIT == 5]
    DELETE FROM table WHERE user_id = ? ORDER BY last_activity LIMIT 1;
}

然而问题是我对这个解决方案不满意。我想或者更愿意只使用一个SQL查询来完成所有这些。

last_activity列的类型为DATETIME

2 个答案:

答案 0 :(得分:1)

当用户超过五行时,您可以在join语句中使用delete删除除最近行之外的所有行:

delete t from table t join
              (select user_id, max(last_activity) as mla
               from table
               group by user_id
               having count(*) > 5
              ) mla
              on t.user_id = mla.user_id and
                 t.last_activity < mla.mla;

这适用于所有用户。对于一个用户,请添加where语句:

delete t from table t join
              (select user_id, max(last_activity) as mla
               from table
               where user_id = '?'
               group by user_id
               having count(*) > 5
              ) mla
              on t.user_id = mla.user_id and
                 t.last_activity < mla.mla;

编辑:

要删除一行,只需使用min()代替max()

delete t from table t join
              (select user_id, min(last_activity) as mla
               from table
               where user_id = '?'
               group by user_id
               having count(*) > 5
              ) mla
              on t.user_id = mla.user_id and
                 t.last_activity = mla.mla;

答案 1 :(得分:0)

要将所有内容保存在单个查询中,您可以使用以下内容:

DELETE FROM table
WHERE
  user_id = ?
  AND last_activity = (SELECT * FROM
   (SELECT CASE WHEN COUNT(*)>5 THEN MIN(last_activity) END
    FROM table
    WHERE user_id = ?) s)
如果有超过5个活动,

子查询将返回第一个last_activity,DELETE查询将删除它。否则它将返回NULL并且不会删除任何行。