Imagine a MySql table like this:
---------------------------
ListID | itemID | Item
---------------------------
List_1 | item_1 | Apple
---------------------------
List_1 | item_2 | Orange
---------------------------
List_1 | item_3 | Pear
---------------------------
List_2 | item_1 | Potatoes
---------------------------
List_2 | item_2 | ...
I have a getNextItem() function which increments the itemID and use a SQL query to get the next item:
SELECT * FROM items_tbl
WHERE listID = "$listId"
AND itemID = "$itemID"
LIMIT 1
Is there an easy way in SQL to figure out if the item I am getting is the last one of that list?
I could add a column to the table and mark the last item of each list, or I could make another query, get the highest item number and compare with my list the current item, or get the total number of items in the list and keep track of the item number in relation to the list’s total… but all these solutions feel like a hack.
Can someone suggest something better in SQL and explain a bit how it works?
You did not state your DBMS, but the following is an ANSI compliant SQL (should work on PosgreSQL, Oracle, DB2)
Edit, the following should work on SQL Server (as that doesn’t yet support
lead()):