in reply to Re: Calculating previous/next from database
in thread Calculating previous/next from database

A problem I see with this approach would be sending three queries to the database each time it loads. One for ++, one for --, and the one the OP is using for the real query.
  • Comment on Re^2: Calculating previous/next from database

Replies are listed 'Best First'.
Re^3: Calculating previous/next from database
by dragonchild (Archbishop) on May 31, 2008 at 17:09 UTC
    Meh. If your requirement is a single query, then you need to implement a linked list in the database. This isn't that hard, but it requires that all inserts and deletes update 3 rows vs. just selects doing three queries. This probably is ok.
    CREATE TABLE images ( id INT ,prev_id INT ,next_id INT ,other_columns_here );
    Then, to get everything in a single query, you do:
    SELECT * FROM images WHERE ( (id=?) OR (next_id=?) OR (prev_id=?) );
    Not that hard. :-)

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re^3: Calculating previous/next from database
by parv (Parson) on May 31, 2008 at 08:06 UTC

    Only if this could work ...

    -- changed "union" to "union all" select id from table where id > ? order by id asc limit 1 UNION ALL select id from table where id < ? order by id desc limit 1

    ... does not work in Sybase for (a) "order by" clause does not go with "union all" or in derived table creation; (b) there is no "limit" clause, just "rowcount" option per SQL session/transaction.

      You can do it in a little more convoluted way not using UNION at all:

      SELECT * FROM table WHERE id=(SELECT id FROM table WHERE id>? ORDER BY id ASC LIMIT 1) OR id=(SELECT id FROM table WHERE id<? ORDER BY id DESC LIMIT 1)

      Careful with that hash Eugene.