For example, I currently have 999 pieces of data with IDs ranging from 1 to 1000. How can I use SQL statements to find out what the missing ID is?
PS: What if two pieces of data are missing?
For example, I currently have 999 pieces of data with IDs ranging from 1 to 1000. How can I use SQL statements to find out what the missing ID is?
PS: What if two pieces of data are missing?
<code>(1+2+...+1000) - sum(id) 不就行了吗?</code>
<code>第一个 select t.id from (select @rownum:=@rownum+1 no,id from table, (SELECT @rownum:=0) r)t where t.no - t.id = 1 limit 1 第二个 select t.id from (select @rownum:=@rownum+1 no,id from table, (SELECT @rownum:=0) r)t where t.no - t.id = 2 limit 1</code>
It is not recommended to use SQL
statements to perform such complex operations. Instead of increasing the burden on the database, it is better to let PHP
bear it~
<code><?php $arr = [1,4,8,9,10,20]; // 假设这是从数据库中读取出来的ID数组 $res = []; for ($i = 0; $i < count($arr)-1; $i++) { if (($num = $arr[$i+1] - $arr[$i]) > 1) { for ($j = 1; $j < $num; $j++) { $res[] = $arr[$i] + $j; } } } var_dump($res);</code>