删除帐户中的所有行,最近的十一行除外

时间:2014-07-19 21:40:18

标签: sql mysqli

提交评论后,我尝试运行一个查询,删除所有匹配帐号的行,但最近的十一行除外。我的表格包括"帐号","邮票"(日期时间)和"评论"。

帐号以变量$account传递。

mysqli_query($sqli, "
    DELETE FROM table 
    WHERE account='$account'
    AND stamp NOT IN (SELECT stamp FROM table ORDER BY stamp DESC LIMIT 11)
");

不确定查询有什么问题:/:D

1 个答案:

答案 0 :(得分:1)

您可以使用deletejoin

执行此操作
delete t
    from table t left join
         (select t.*
          from table t
          where account = $account
          order by stamp desc
          limit 11
         ) tt
         on t.account = tt.account and t.stamp = tt.stamp
    where t.account = $account and tt.account is null;