mysql select inside limit

2019-07-18 03:42发布

问题:

select
  id
from
  tableABC
limit (select count(id) from tableCBA), 1

If I need select in limit as I have shown here in sample code, how can I do this in mySql? This is only simplified code for purpose of this forum, otherwise this is a part of sophisticated case when else select.

回答1:

You can't directly have a dynamic value for limit, but your query can be re-written without the limit, as follows:

set i := (select count(*) from tableCBA);
select id
from tableABC
where (i := i-1) = 0;

This will return the nth row, where n is the number of rows in tableCBA;



回答2:

select @LimitRowsCount1=count(id) from tableCBA;

PREPARE STMT FROM "SELECT id from tableABC LIMIT ?";

EXECUTE STMT USING @LimitRowsCount1;