tags:

views:

122

answers:

3

I want to do a query to retrieve the record immediately after a record for any given record, in a result set ordered by list. I do not understand how to make use of the limit keyword in sql syntax to do this.

I can use WHERE primarykey = number, but how will limiting the result help when I will only have one result?

How would I obtain the next record with an arbitrary primary key number?

I have an arbitrary primary key, and want to select the next one ordered by date.

+3  A: 

This will emulate the LEAD() analytic function (i. e. select the next value for each row from the table)

SELECT  mo.id, mo.date,
        mi.id AS next_id, mi.date AS next_date
FROM    (
        SELECT mn.id, mn.date,
               (
               SELECT  id
               FROM    mytable mp
               WHERE   (mp.date, mp.id) > (mn.date, mn.id)
               ORDER BY
                       mp.date, mp.id
               LIMIT 1
               ) AS nid
        FROM   mytable mn
        ORDER BY
               date
        ) mo,
        mytable mi
WHERE mi.id = mo.nid

If you just want to select next row for a given ID, you may use:

SELECT  *
FROM    mytable
WHERE   (date, id) >
        (
        SELECT  date, id
        FROM    mytable
        WHERE   id = @myid
        )
ORDER BY
        date, id
LIMIT 1

This will work most efficiently if you have an index on (date, id)

Quassnoi
That looks crazy..is it really necessary to have 3 nested queries?
Joshxtothe4
If you need only the next NID, you may get rid of the outermost query, just select NID. This query is fast, and disk space is pretty cheap now, so "long queries" does not mean "costly queries" :)
Quassnoi
The second query here looks like pretty much exactly what you want (though I don't see why you bother retrieving `id` in the subquery except to break duplicates).
kquinn
Yes, it's to handle duplicates. If there are two records with same datetime: (1, '2009-01-01') and (2, '2009-01-01'), and you pass 1 as @myid, then 2 will be never selected if you don't put an id into the subquery.
Quassnoi
+1  A: 

How about something like this, if you're looking for the one after 34

SELECT * FROM mytable WHERE primaryKey > 34 ORDER BY primaryKey LIMIT 1
Jesse Rusak
I have an arbitrary primary key, and want to select the next one ordered by date, so I dont think will work.
Joshxtothe4
+1  A: 

Might be as simple as:

select *
from mytable
where datecolumn > (select datecolumn from mytable where id = @id)
order by datecolumn
limit 1

(Edited after comments)

Andomar
There is no TOP 1 in MySQL
Quassnoi
I have an arbitrary primary key, and want to select the next one ordered by date, so I dont think will work.
Joshxtothe4
What if there are duplicates of datecolumn?
Quassnoi
Right-- I'll just vote for your solution instead of editing mine:)
Andomar