2014-11-03 42 views
0

你能告訴我如何刪除未知數最後一條記錄(條件)?如何刪除未知號碼的最後一條記錄(條件)?

例如,在這種情況下,我想刪除記錄的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 | 
+----+-----+---------+ 

謝謝...

+0

您的問題仍然沒有清除您不恆定 – 2014-11-03 12:19:09

+0

不恆定的意思!它是varchar類型嗎?你什麼意思 ? – DeepInJava 2014-11-03 12:21:02

+0

@SanketPipariya請原諒我的英語不好!這張表和記錄是不恆定的。 – Daniyal 2014-11-03 12:22:48

回答

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,有沒有後續emailids是不爲零。

可以使用join要把它放到delete

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; 
+0

坦克爲你的答案,這個查詢只刪除一行,我想刪除所有6-10行。 – Daniyal 2014-11-03 12:28:22

+0

@Daniyal。 。 。邏輯倒置。在子查詢中應該是'<> 0',而不是'= 0'。 – 2014-11-03 12:32:18

0

您可以使用關鍵字between在查詢中這樣

delete from yourtable where id BETWEEN 6 AND 10 
+0

6到10是不恆定的! – Daniyal 2014-11-03 12:17:21

+0

@Daniyal - 數字是否正確?什麼是id列的數據類型? – DeepInJava 2014-11-03 12:18:03

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" 
相關問題