为什么这个sql可以在准备后执行成功?

时间:2018-02-01 02:33:49

标签: mysql prepared-statement mybatis spring-mybatis

哼,今天我发现了一个关于sql的问题

SELECT * FROM tb_users where deleteFlag != 1 ORDER BY createTime LIMIT 0, ?   

来自mybatis xml:

<select id="findListByNearly" resultType="org.destiny.model.User">
    SELECT
        <include refid="Base_Column_List"/>
    FROM tb.users
    WHERE status != 0
    ORDER BY createTime
    LIMIT 0, #{count}
</select>

我错误地通过

调用
count = -1

它工作正常 但是当我立即执行时

SELECT * FROM tb_users where deleteFlag != 1 ORDER BY createTime LIMIT 0, -1

MySQL返回错误信息如下:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1' at line 1

我知道如果我立即按LIMIT 0, -1执行导致错误的语法,它将无法工作

但为什么它可以在准备后工作?

springboot的日志:

==>  Preparing: SELECT id, typeName, standardWeight, standardCube, standardHeight, status, createTime, updateTime FROM TB_YX_TMS_CAR_TYPES WHERE status != 0 AND (standardCube > 19.4) ORDER BY (standardCube - 19.4) LIMIT 0, ? 
==> Parameters: -1(Integer)
<==    Columns: id, typeName, standardWeight, standardCube, standardHeight, status, createTime, updateTime
<==        Row: 4, type4, 0.0, 19.7, null, 1, 0, 0
<==        Row: 2, type2, 0.0, 20.2, null, 1, 0, 0
<==        Row: 3, type3, 0.0, 20.9, null, 1, 0, 0
<==      Total: 3

=============================================== ======================

我在mysql客户端上测试过,发现它在mysql-prepare之后没有工作: when I invoked by -1, it returns a error

但为什么它在mybatis中有效?

1 个答案:

答案 0 :(得分:0)

因为LIMIT关键字的正确语法是

[LIMIT {[offset,] row_count | row_count OFFSET offset}]
  

使用两个参数,第一个参数指定的偏移量   第一行返回,第二行指定最大数量   要返回的行。 初始行的偏移量为0 (不是1):

根据文档, 无法 拥有negative offset