MySQL 最小缺失值問題

神諭丶發表於2014-08-21
首先通過建立表和插入構建一個測試環境
  1. create table missed_minimum(
  2. a int unsigned primary key,
  3. b char(1) not null);


  1. insert into missed_minimum select 1,'z';
  2. insert into missed_minimum select 2,'x';
  3. insert into missed_minimum select 3,'a';
  4. insert into missed_minimum select 4,'b';
  5. insert into missed_minimum select 6,'c';
  6. insert into missed_minimum select 7,'d';
  7. insert into missed_minimum select 9,'e';

最小缺失值問題是找出記錄中不連續的最小值,即在此表資料的情況下,則查詢應該返回5


解決方案一 (通過exists解決)

  1. select min(a)+1 as missming
  2. from missed_minimum a
  3. where not exists (select *
  4.                  from missed_minimum b
  5.                  where a.a+1=b.a);


解決方案二 (通過outer join解決)


  1. select min(a.a)+1 as missming
  2. from missed_minimum a
  3.     left join missed_minimum b
  4.     on a.a+1 = b.a
  5. where y.a is null;
按照方案二給出思路
  1. select a.*,b.*
  2. from missed_minimum a
  3.     left join missed_minimum b
  4.     on a.a+1 = b.a;
得出 通過a.a+1 = b.a可以找出a列中所有不連續的缺失值(方案一的子查詢原理一樣)



在上述sql語句加上where y.a is null (方案一通過not exists得出a列是4、7、9)
得出


最後再用min(a.a)+1處理
得出最小缺失值為5





來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29773961/viewspace-1255436/,如需轉載,請註明出處,否則將追究法律責任。

相關文章