如何 select 带有 id 的行仅在空白上方

how to select the rows with id's just one above gaps

我有一个 table 包含列 idname。我的重点是 id 的顺序。事实上,我想要 select 行,当数字的 id 顺序中断时。看我的例子:

// mytable
+----+-----------+
| id |    name   |
+----+-----------+
| 1  |   ali     |
| 2  |   jack    |
| 3  |   peter   |
| 5  |   steve   |
| 6  |   lenord  |
| 7  |   jack    |
| 9  |   fered   |
+----+-----------+

现在我想 select where id=5select where id=9。因为 id=4id=8 被删除了。

编辑:我想要这个输出:

// mytable
+----+-----------+
| id |    name   |
+----+-----------+
| 5  |   steve   |
| 9  |   fered   |
+----+-----------+

我可以这样做吗?

尝试查找特定 ID。 http://php.net/manual/en/mysqli-result.data-seek.php

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT id, name FROM table";
if ($result = $mysqli->query($query)) {

    /* seek to row no. 4 */
    $result->data_seek(3);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("ID: %s  Name: %s\n", $row[0], $row[1]);

    /* seek to row no. 7 */
    $result->data_seek(6);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("ID: %s  Name: %s\n", $row[0], $row[1]);

    /* free result set*/
    $result->close();
}

/* close connection */
$mysqli->close();
?>

这应该return:

ID: 5 Name: steve
ID: 9 Name: fered

事实上,您想要 id 仅高于 missing id 的记录;所以你需要搜索带有 id 的记录,这样 id-1 确实 不存在 (对于最低 ID 总是如此,所以我们将必须明确排除 id=1 )

SELECT *
FROM the_table tt
WHERE id > 1
AND NOT EXISTS (
   SELECT *
   FROM the_table nx
   WHERE nx.id = tt.id -1
   );
SELECT x.*
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.id = x.id - 1 
 WHERE y.id IS NULL 
   AND x.id > 1;
+----+-------+
| id | name  |
+----+-------+
|  5 | steve | 
|  9 | fered | 
+----+-------+