如何选择id仅在空隙之上的行

时间:2015-06-23 22:02:33

标签: php mysql gaps-in-data

我有一个包含列idname的表格。我的重点是id的顺序。实际上我想选择行,当数字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   |
+----+-----------+

我可以这样做吗?

3 个答案:

答案 0 :(得分:0)

尝试搜索特定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();
?>

这应该返回:

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

答案 1 :(得分:0)

实际上,您希望id <1>的记录仅在缺少 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
   );

答案 2 :(得分:0)

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 | 
+----+-------+