mysql中limit后面不能使用运算符
进行分页查询的时候,如果写成以下sql,语句执行会报错:
- select * from user where id = 123456 and code = 111
- and create_date >= 20190101 and create_date <= 20190202
- limit (1 - 1) * 1, 20
因为mysql中limit后面不能带运算符,只能是常量。
解决方法
使用concat,动态sql。
- set @sql = concat('select* from user where id= 123456 andcode= 111
- and create_date >= 20190101 and create_date <= 20190202 limit', (1-1)*1,',20');
- prepare texts from @sql;
- execute texts;
这种方式说白了就是先计算出数值,再通过concat函数拼接sql,再进行执行。