如何删除未知号码的最后记录(有条件)?

时间:2014-11-03 12:12:30

标签: mysql

你能否告诉我如何删除未知号码的最后记录(有条件)?

例如,在这种情况下,我想删除id为6到10的记录。

注意:此表和记录不是常量。

+----+-----+---------+
| id | url | emailid |
+----+-----+---------+
|  1 |  10 |       1 |
|  2 |  20 |       0 |
|  3 |  30 |       2 |
|  4 |  40 |       0 |
|  5 |  50 |      10 |
|  6 |  60 |       0 |
|  7 |  70 |       0 |
|  8 |  80 |       0 |
|  9 |  90 |       0 |
| 10 | 100 |       0 |
+----+-----+---------+

...谢谢

3 个答案:

答案 0 :(得分:2)

似乎您要删除所有值均为0的最后一组记录。这有点痛苦。您可以找到最小的ID:

select min(t.id)
from table t
where t.emailid = 0 and
      not exists (select 1 from table t2 where t2.id > t.id and t2.emailid <> 0);

逻辑是:查找emailid为0的所有行,并且没有后续的电子邮件不为零。

您可以使用delete

将其加入join
delete t
    from table t cross join
         (select min(t.id) as first0id
          from table t
          where t.emailid = 0 and
                not exists (select 1 from table t2 where t2.id > t.id and t2.emailid <> 0)
         ) tmin
     where t.id >= tmin.first0id;

答案 1 :(得分:0)

您可以在查询中使用between关键字

delete from yourtable where id BETWEEN 6 AND 10

答案 2 :(得分:0)

使用此查询

  delete from your_table where id between 6 AND 10

因为不是常数,你可以先在变量中存储起始值和结束值,然后传入查询,例如(在php中)

 $start = 6 ;
 $end = 10;

查询

   "delete from your_table where id between $start AND $end"