我目前正在开发一个程序,该程序获取表中丢失的 ID,我想到的是将 ID 存储到数组中并使用 for 循环来检查数组中是否存在数字如果存在,则将其归类为丢失 ID。我还使用了 php 函数 - in_array() 来检查数组中是否存在数字。
这是我想出的代码,但我最终只显示 for 循环中的数字。
<?php
include 'dbconnect.inc'; //just to the the dbconnect for connecting into the database.
$numbers = array(1, 2, 4, 6, 7, 9);
$arrlength = count($numbers);
$query = "SELECT id FROM existing";
$result = mysqli_query($conn, $query);
$existing = array();
while ($row = mysqli_fetch_assoc($result)) {
$existing[] = $row;
}
for ($i=0; $i<7358; $i++) {
if (in_array($i, $existing)) {
echo $i . " is a missing ID <br>";
} elseif(!in_array($i, $existing)) {
echo $i . " exists in the table <br>";
}
}
?>
与在 SQL 中使用临时表相比,我更喜欢此解决方案,因为它需要的不仅仅是加载查询,而且对于网页来说并不好。
希望你能帮助我。谢谢!
最佳答案
来自this answer :
要获取缺失的范围:
SELECT a.id+1 AS 'Missing From', MIN(b.id)-1 AS 'Through'
FROM existing AS a
JOIN existing AS b ON a.id < b.id
GROUP BY a.id
HAVING a.id+1 < MIN(b.id)
关于php - 通过将记录存储到数组中获取表中缺失的 ID,并使用 for 循环比较该组数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348963/