I have a table with N rows, and I wanna select N-1 rows.
Suggestions on how to do this in one query, if it's possible..?
I have a table with N rows, and I wanna select N-1 rows.
Suggestions on how to do this in one query, if it's possible..?
Does the last row have the highest ID? If so, I think this would work:
SELECT * FROM TABLE WHERE ID != (SELECT MAX(ID) FROM TABLE)
MySQL does allow subselects in the current version, right?
However, in most cases, it'd probably perform better if you selected all the rows and then filtered the unwanted data out in your application.
Another technique I don't see listed here is
SELECT * FROM table ORDER BY id DESC LIMIT 10000 OFFSET 1;
This will give you the records ordered by id descendant except first, that is except the last in the original order.
Note that with this method you will only take 10000 records, however this number can be as high as you want but cannot be omitted.
The advantage of this method is that you can order by whatever you want.
The disadvantage is that it gives you the records ordered from last to first.
Finally it worths noting that the other methods here works quite well
SELECT DISTINCT t1.columns FROM table t1
INNER JOIN table t2 ON t1.id < t2.id
In my experience, MySQL loves this technique, going back several versions.
you must DECLARE a variable and after that SET it. With the help of LIMIT you'll find the n-1 rows
like this:
DECLARE rowsNr INT DEFAULT 0;
SET rowsNr = SELECT (count(*) AS 'TOTAL_ROWS' FROM TABLE;
SET rowsNr = rowsNr -1;
SELECT * FROM Table WHERE ... LIMIT rowsNr;
if it doesn't work on a normal query try to place it in a StoredProcedure
Another way to do this could be:
SELECT * FROM table WHERE ID <> LAST_INSERT_ID()
Reference: http://dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html