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是不存在这张表里的)

所以看结果

就可以直接知道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写错了大笑

如图

和前面是一样的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值