mysql关键字的坑

MySQL5.7关键字点这里

SQL(Structured Query Language)是第四代语言,和第三代语言(例如C++,Java)一样,也有自己的关键字,而不同数据库的关键字也不尽相同,上周使用mysql5.7版本的时候就遇到了一个坑。

SELECT count(order_no)
FROM order_info
WHERE
1=1
and
status = 0
and
type = 0

在mysql库中直接查询数据得出正确结果,下面是mysql映射文件中的写法:

<select id="*****" resultMap="BaseResultMap">
        SELECT  
	count(order_no)
FROM order_info WHERE 1 = 1 <if test="status != null"> and status = #{status,jdbcType = TINYINT} </if> <if test="type != null "> and type = #{type,jdbcType=TINYINT} </if> </select>
 然后页面得出的结果比实际结果大很多,结果发现了没有执行type的条件,只执行了status,原因不明确,因为以前遇到过关键字错误,觉得应该是type的问题,于是改代码: 
 

<select id="*****" resultMap="BaseResultMap">
        SELECT  
	count(order_no)
        FROM order_info
        WHERE
        1 = 1
        <if test="status != null">
            and status = #{status,jdbcType = TINYINT}
        </if>
        <if test="`type` != null ">
            and `type` = #{type,jdbcType=TINYINT}
        </if>
    </select>
发现结果还是不对。于是找问题,找了一会儿发现好像没有执行status条件了,然后去查了mysql5.7的关键字,果然,status也是关键字,改成了:

<select id="*****" resultMap="BaseResultMap">
        SELECT  
	count(order_no)
        FROM order_info
        WHERE
        1 = 1
        <if test="`status` != null">
            and `status` = #{status,jdbcType = TINYINT}
        </if>
        <if test="`type` != null ">
            and `type` = #{type,jdbcType=TINYINT}
        </if>
    </select>
结果正确!

在设计数据库的时候尽量考虑到关键字因素,有时候一个小小的字段坑起来,连bug都不知道在哪里出来的。

猜你喜欢

转载自blog.csdn.net/qq_26400953/article/details/78887366