检查mysql ID是否跳过php


Check for mysql ID skips php

说在mysql中我有一个列id,只是int自动增量。

是否有任何方法我可以使用php告诉我,当有一个id被删除?

比如我有

567810

我需要它告诉我9丢失了,并对所有id继续这样做。有什么办法可以做到吗?

谢谢

您需要一个包含所有值的表。然后很容易执行左连接来查找丢失的id。

create table all_values
(id int not null) engine = myisam;
insert into all_values (id) values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
create table existing_values like all_values;
insert into existing_values (id) values (5),(6),(7),(8),(10);
select a.id from all_values as a
left join existing_values as b
on a.id = b.id
where b.id is null

有一种方法:
1. 从表中选择所有id。
2. 将它们全部传递给%hash:
5 => 1
6 => 1
7 => 1
8 => 1
10 => 1

你的ID是哈希值的一个键值是1

    创建for循环

for ($i = 1;美元我& lt;11;美元我+ +)
{
  if($hash{$i} != 1)
,, {
      打印"ID $i缺失'n";
,,}
}

这是Perl语法,但PHP应该非常相似。

如果您可以接受在数据库中的第一个id 之前没有空白(以及使用'临时表','文件格式'和'join buffer'进行查询):

SELECT
    a.id + 1 AS `From`,
    MIN(b.id - 1) AS `To`
FROM
    foo as a, foo as b
WHERE
    a.id < b.id
GROUP BY
    a.id
HAVING
    a.id < min(b.id) -1

自包含的例子:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// usually I create temporary tables for example scripts, but
// self-joins don't work on temp tables in mysql, bare me....
$pdo->exec('CREATE TABLE soFoo ( id int, primary key(id))');
$pdo->exec('INSERT INTO soFoo (id) VALUES (5),(6),(7),(8),(10),(15),(21)');
foreach( $pdo->query('
    SELECT
        a.id + 1 AS `From`,
        MIN(b.id - 1) AS `To`
    FROM
        foo as a, foo as b
    WHERE
        a.id < b.id
    GROUP BY
        a.id
    HAVING
        a.id < min(b.id) -1', PDO::FETCH_ASSOC) as $row
) {
    echo $row['From'], ' - ', $row['To'], "'n";
}

打印

9 - 9
11 - 14
16 - 20