2

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 
revo
  • 47,783
  • 14
  • 74
  • 117

1 Answers1

0

It seems you want to exclude the highest 5 ids and sort the results by id descending. To do this you can just start the limit at 5:

Set @a = (Select Count(*) From table);
Prepare stmt From 'Select * From table Order By id desc Limit 5, ?';
Execute stmt Using @a;

To see how this works, imagine the results (id only) before the limit is applied:

55, 54, 53, 52, 51, 50, 49, ...

Limit 5, n says to return n rows starting from the 6th, i.e

50, 49, ...

Here @a just needs to be big enough to get all the results. You could just use a very big number and not worry about being precise. Assuming id is unique, max(id) or count(*) will do in this case.

Laurence
  • 10,896
  • 1
  • 25
  • 34