sql >> データベース >  >> RDS >> Mysql

現在の行の次または前の行の行をプルするsql

    これは、前/次のレコードを見つけるために使用するものです。テーブル内の任意の列を並べ替え列として使用でき、結合や厄介なハックは必要ありません:

    次のレコード(現在のレコードよりも大きい日付):

    SELECT id, title, MIN(created) AS created_date
    FROM photo
    WHERE created >
      (SELECT created FROM photo WHERE id = '32kJ')
    GROUP BY created
    ORDER BY created ASC
    LIMIT 1;
    

    前のレコード(現在のレコードより前の日付):

    SELECT id, title, MAX(created) AS created_date
    FROM photo
    WHERE created <
      (SELECT created FROM photo WHERE id = '32kJ')
    GROUP BY created
    ORDER BY created DESC
    LIMIT 1;
    

    例:

    CREATE TABLE `photo` (
        `id` VARCHAR(5) NOT NULL,
        `title` VARCHAR(255) NOT NULL,
        `created` DATETIME NOT NULL,
        INDEX `created` (`created` ASC),
        PRIMARY KEY (`id`)
    )
    ENGINE = InnoDB;
    
    INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('XEi43', 'my family',       '2009-08-04');
    INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('dDls',  'friends group',   '2009-08-05');
    INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('32kJ',  'beautiful place', '2009-08-06');
    INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('EOIk',  'working late',    '2009-08-07');
    
    SELECT * FROM photo ORDER BY created;
    +-------+-----------------+---------------------+
    | id    | title           | created             |
    +-------+-----------------+---------------------+
    | XEi43 | my family       | 2009-08-04 00:00:00 |
    | dDls  | friends group   | 2009-08-05 00:00:00 |
    | 32kJ  | beautiful place | 2009-08-06 00:00:00 |
    | EOIk  | working late    | 2009-08-07 00:00:00 |
    +-------+-----------------+---------------------+
    
    
    SELECT id, title, MIN(created) AS next_date
    FROM photo
    WHERE created >
      (SELECT created FROM photo WHERE id = '32kJ')
    GROUP BY created
    ORDER BY created ASC
    LIMIT 1;
    
    +------+--------------+---------------------+
    | id   | title        | next_date           |
    +------+--------------+---------------------+
    | EOIk | working late | 2009-08-07 00:00:00 |
    +------+--------------+---------------------+
    
    SELECT id, title, MAX(created) AS prev_date
    FROM photo
    WHERE created <
      (SELECT created FROM photo WHERE id = '32kJ')
    GROUP BY created
    ORDER BY created DESC
    LIMIT 1;
    
    +------+---------------+---------------------+
    | id   | title         | prev_date           |
    +------+---------------+---------------------+
    | dDls | friends group | 2009-08-05 00:00:00 |
    +------+---------------+---------------------+
    


    1. SQLServerでのAlwaysOn可用性グループの構成

    2. 許容されるメモリサイズ134217728バイトが使い果たされました(42バイトを割り当てようとしました)

    3. SQLServerのカーソルタイプ-SQLServerの静的カーソルとは| SQLServerチュートリアル/TSQLチュートリアル

    4. SQLServerでのCXPACKETおよびCXCONSUMER待機タイプのわかりやすさ