say in mysql I have a column that's id, just int auto increment.
Is there any way I can use php to tell me when there is an id that's been removed?
Like say i have
5 6 7 8 10
I need it to tell me that the 9 is missing, and continue this for all the id's. Is the开发者_高级运维re any way to do this?
Thanks
You need a table that contains all values. Then it's simple to do a left join to find missing ids.
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
Here is one way to do it:
1. Select all IDs from the table.
2. Assing them all to a %hash:
5 => 1
6 => 1
7 => 1
8 => 1
10 = > 1
So your ID is a key of the hash and the value is 1.
- Create a for loop
for (my $i = 1; $i < 11; $i++)
{
if($hash{$i} != 1)
{
print "ID $i is missing \n";
}
}
This is Perl syntax, but PHP should be pretty similar.
If you can live with not getting a gap before the first id in the database (and a query using 'temporary table', 'filesort' and '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
self-contained example:
<?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";
}
prints
9 - 9
11 - 14
16 - 20
精彩评论