Home > Backend Development > PHP Tutorial > How to find out the missing data

How to find out the missing data

WBOY
Release: 2016-09-24 09:15:08
Original
1343 people have browsed it

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?

Reply content:

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>
Copy after login
<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>
Copy after login

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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template