I've a dynamic SQL query:
SET @a=(SELECT MAX(ID) FROM table);
PREPARE STMT FROM 'SELECT * FROM table ORDER BY id DESC LIMIT 0, ?';
EXECUTE STMT USING @a;
That works correctly as expected. However I wanna subtract last 5 rows from this query.
So I used two ways:
1- SET @a=(SELECT (MAX(ID)-5) FROM table);
2- SET @a := @a-5;
The weird thing here is that, it runs but results don't have any differences from the intact query and all rows are fetched!
Any explanations on this topic is really appreciated.
Update #1
There is no gap in the last 20 rows, also if I change 5 to a bigger number like 200 the results are the same.
Update #2
SELECT COUNT(*), MAX(ID) FROM table outputs 211 for COUNT(*) & 577 for MAX(ID)
So if I change 5 to 400 it works, but it excludes first 34 IDs from the result. Also this way of exclusion is true about @Laurence answer.
Update #3
Consider these IDs as total rows in the table table.
| ID |
+----+
| 55 |
| 54 |
| 53 |
| 52 |
| 51 |
See the results about below changes to the query (order is DESC as I defined):
# @a is MAX(id) = 55
SET @a := @a-5;
=> query: SELECT * FROM table ORDER BY id DESC LIMIT 0, 55-5/*50*/ -- no effects in result
SET @a := @a-50;
=> query: SELECT * FROM table ORDER BY id DESC LIMIT 0, 55-50/*5*/ -- no effects in result
SET @a := @a-51;
=> query: SELECT * FROM table ORDER BY id DESC LIMIT 0, 55-51/*4*/ -- will exclude row `51` from the result so `55, 54, 53, 52` are fetched