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

84 views Asked by At

I have a table containing columns id and name. My focus is on order of id. In fact I want to select the rows, When order of number's id breaks . Look at my example:

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

Now I want to select where id=5 and select where id=9. because id=4 and id=8 are removed.

EDIT: I want this output:

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

Is it possible to I do that ?

3

There are 3 answers

4
wildplasser On BEST ANSWER

In fact you want the records with id's just one above the missing id's; so you need to search fo the records with id such that id-1 does not exist (this will always be the case for the lowest id, so we'll have to explicitely exclude id=1 )

SELECT *
FROM the_table tt
WHERE id > 1
AND NOT EXISTS (
   SELECT *
   FROM the_table nx
   WHERE nx.id = tt.id -1
   );
2
Twisty On

Try seeking versus a specific 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();
?>

This should return:

ID: 5 Name: steve
ID: 9 Name: fered
1
Strawberry On
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 | 
+----+-------+