How to select non-consecutive rows in MySQL?

前端 未结 5 1511
终归单人心
终归单人心 2021-01-13 07:08

If the primary keys of the records are 1,3,4,5,6,8

I want to select the records with pk:1,6

NOTE

I don\'t

相关标签:
5条回答
  • 2021-01-13 07:42
    SELECT *
    FROM your_table AS a
        LEFT JOIN your_table AS b
            ON a.key_column = b.key_column - 1
    WHERE b.key_column IS NULL
    
    0 讨论(0)
  • 2021-01-13 07:42

    Why not use a where clause in your SQL query ?

    select *
    from your_table
    where id in (1, 6)
    
    0 讨论(0)
  • 2021-01-13 07:51

    A little improvement for the solution proposed by Robin Day

    SELECT
        [MyId] + 1
    FROM
        [MyTable]
    WHERE
        [MyId] NOT IN
    (
        SELECT
            [MyId] - 1
        FROM
            [MyTable]
    )
    ORDER BY [MyId] + 1
    
    0 讨论(0)
  • 2021-01-13 07:54

    What about something like this?

    SELECT
        *
    FROM
        [MyTable]
    WHERE
        [MyId] NOT IN
    (
        SELECT
            [MyId] - 1
        FROM
            [MyTable]
    )
    
    0 讨论(0)
  • 2021-01-13 08:03

    Remember, in your DB of choice, rows generally aren't "consecutive" unless you specifically ORDER them. They just often happen to come out in the right order when you don't specify an order by.

    0 讨论(0)
提交回复
热议问题