简体   繁体   中英

SQL - Best practice way of cycling through rows by Date

Im working on a JAVA form and SQLite Database driven app that takes in some information for each day and sometimes multiple times in a day.

The input form and Database would look like this

输入表格

数据库布局

What i would like to do is have the ability to press "Next record" or "Previous Record" and it will go to the next record by Date but the record could have the same day set.

If i go by ID theres no way of it not messing up when i delete rows. If someone comes in and edits an old record date it will also mess up the cycle if i go by ID.

How to developers generally cycle through records like this?

Thanks

I would suggest a Date/ID index (assmuing there are no other criteria), and then use these columns as part of your ORDER BY . This will ensure all records on the same day, maintain a consistent order.

You can also use relative filters to the current record this way ie

WHERE (new.date = old.date AND new.ID > old.ID)
OR new.date > old.date

combine this with your ordering, and you'll have the 'next record' as your first result each time.

previous is similar - just reverse the criteria.

The resulting query should look something like:

SELECT   TOP 1 *
FROM     Table t
WHERE    (t.Date = old.Date AND t.ID > old.ID)
OR       t.Date > old.Date
ORDER BY Date, ID

The old.Date and old.ID are parameters passed in (am guessing SQLite uses a similar TOP to MSSQL, as opposed to Rownum or limits).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM