文章已参与[新人创作礼]活动,一起开启掘金创作之路.
微信公众号:秀基宝。如有问题,请后台留言,反正我也不会听。
前言
最近写查询时候报了一个莫名其妙的报错,我还以为是sql写的有问题,贴下原sql和新sql
一、报错
### Cause: java.sql.SQLSyntaxErrorException: 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 '(`gmt_create`, '%Y-%m-%d %H:%i:%s') gmtCreate, su.nick creator LEFT JOIN (SELECT' at line 1
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: 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 '(`gmt_create`, '%Y-%m-%d %H:%i:%s') gmtCreate, su.nick creator LEFT JOIN (SELECT' at line 1
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
二、原sql
<if test="phaseTime != null and phaseTime != ''">
and phase_time like
<foreach item="index" collection="phaseTime.split(',')" open="(" separator="," close=")">
concat("%",#{index},"%")
</foreach>
</if>
三、问题所在
看上面sql,粗略看没啥问题,就是遍历字段然后like查询,但是仔细一看不同字段之间应该是or相隔开,也就是like 'a' or 'b',而上面打印出来就是phase_time like ( a, b),执行起来其实是报错的。
四、新sql
<!--循环模糊匹配-->
<if test="phaseTime != null and phaseTime != ''">
and (
<foreach item="index" collection="phaseTime.split(',')" open="(" separator="or" close=")">
phase_time like concat("%",#{index},"%")
</foreach>
)
</if>
编译后sql
AND ( ( phase_time LIKE concat( "%",?, "%" ) OR phase_time LIKE concat( "%",?, "%" ) ) )
接着去除上面那个and后面括号就可以了,这样可以查出数据
五、结论
其实这句话的意思是:操作数应包含1列 遇到问题不要急,找准那个部位的sql,再查是sql问题还是mybatis用法问题,肯定鞥解决的
本人开发的玩基金小工具
个人博客:
名称:纯洁的麦田
链接:[http://www.idearyou.cn/]
描述:争取哪一天做上架构师
公众号:纯洁的麦田
网址:[xiu.idearyou.cn]
谷歌插件搜:秀基宝
小程序:秀基宝
复制代码
复制代码
复制代码
后语
如果本文对你哪怕有一丁点帮助,请帮忙点好看。你的好看是我坚持写作的动力。 另外,关注免费学习。