• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

mysql 查寻不存在的id_mysql

mysql 搞代码 7年前 (2018-06-07) 276次浏览 已收录 0个评论

mysql 查找不存在的id

最近在群里有人问到怎样才能将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是不存在这张表里的)

所以看结果mysql 查寻不存在的id_mysql

就可以直接知道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_mysql

如图mysql 查寻不存在的id_mysql

和前面是一样的。

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

欢迎大家阅读《mysql 查寻不存在的id_mysql》,跪求各位点评,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:mysql 查寻不存在的id_mysql

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址