首页 > 数据库技术 > 详细

mysql 查找不存在的id

时间:2015-08-19 23:43:35      阅读:1014      评论:0      收藏:0      [点我收藏+]

最近在群里有人问到怎样才能将mysql表中 查找不存在的id(id自增,或者连续都可以)

第一种方法:

select bewin_id,a from

(
select bewin_id,1 as a from (select bewin_id from c_userinfo_his order by bewin_id asc) t where not exists (select 1 from c_userinfo_his where bewin_id=t.bewin_id-1)
union
select bewin_id,2 as a from (select bewin_id from c_userinfo_his order by bewin_id asc) t where not exists (select 1 from c_userinfo_his where bewin_id=t.bewin_id+1)

) t order by bewin_id

解释下select bewin_id,1 as a from (select bewin_id from c_userinfo_his order by bewin_id asc) t where not exists (select 1 from c_userinfo_his where bewin_id=t.bewin_id-1)

这个sql查到的id都是缺少这个id的前一个id(有点拗口,举例就是查到的id为7则6是不存在这张表里的)

select bewin_id,2 as a from (select bewin_id from c_userinfo_his order by bewin_id asc) t where not exists (select 1 from c_userinfo_his where bewin_id=t.bewin_id+1)

这个sql查到的id都是缺少这个id的后一个id(举例就是查到的id为7则8是不存在这张表里的)

所以看结果技术分享

就可以直接知道456和1213等等都是不存在的,上面的有个缺点就是要自己去数

第二种方法

创建一张表(c_userinfo_his_test)只有id和另一个字段test,并且id是连续的,最大的id为select max(bewin_id) from c_userinfo_his,这样得到一张完整的id(insert into c_userinfo_his_test(test) values (‘1‘)使bewin_id等于max(bewin_id)),

然后就是执行select bewin_id from c_userinfo_his_tset where bewin_id not in (select bewin_id from c_userinfo_his)

这个语句就可以得到想要的结果了(这里test写错了技术分享

如图技术分享

和前面是一样的。

版权声明:本文为博主原创文章,未经博主允许不得转载。

mysql 查找不存在的id

原文:http://blog.csdn.net/u011575570/article/details/47789581

(0)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!