如何在Bookshelf中对日期列使用LIKE操作符?报错求助
解决DATE类型字段使用LIKE操作符报错的问题
这个问题我之前踩过同款坑!根源很明确:DATE类型字段不能直接用LIKE操作符——LIKE是专门为STRING类型设计的,从你给出的错误信息(42883错误、PostgreSQL的提示)来看,你的数据库里没有针对DATE与字符串进行LIKE匹配的内置操作符,所以才会报错。另外你代码里给LIKE的值加了双引号,这也会让数据库把它当成标识符而非字符串值,雪上加霜。
下面给你两种可行的解决方案,按需选择:
方案1:将DATE转成字符串后使用LIKE(适合模糊匹配场景)
如果确实需要用模糊匹配(比如匹配特定年月的所有日期),可以用数据库的日期转字符串函数(PostgreSQL里是TO_CHAR),把DATE类型转成字符串后再用LIKE。注意不要手动加引号,用参数化查询更安全:
router.route('/fetchStudentAttendance').post(function(req, res) { StudentAttendance .query(function(qb) { // 用TO_CHAR把date转成YYYY-MM-DD格式的字符串,再做LIKE匹配 qb.whereRaw('TO_CHAR(date, \'YYYY-MM-DD\') LIKE ?', ['2018-01%']); }) .where({'class_id': req.body.class_id, 'section_id': req.body.section_id}) .fetchAll() .then(studentAttendance => { let content = { data: studentAttendance, success: true, message: studentAttendance.length > 0 ? 'Records fetched successfully' : 'Record Not Found', }; return res.send(content); }) .catch(error => { let content = { data: error, success: false, message: 'Error while fetching Student Attendance.', }; return res.send(content); }); });
方案2:使用日期范围查询(推荐,性能更优)
如果你的需求只是查询某一月份的所有记录(比如2018年1月),强烈推荐用日期范围查询——这种写法不需要转换数据类型,数据库可以直接利用DATE字段的索引,查询速度更快,结果也更准确(不用纠结当月天数):
router.route('/fetchStudentAttendance').post(function(req, res) { StudentAttendance .query(function(qb) { // 匹配2018年1月的所有日期,不用纠结当月天数 qb.where('date', '>=', '2018-01-01') .where('date', '<', '2018-02-01'); }) .where({'class_id': req.body.class_id, 'section_id': req.body.section_id}) .fetchAll() .then(studentAttendance => { let content = { data: studentAttendance, success: true, message: studentAttendance.length > 0 ? 'Records fetched successfully' : 'Record Not Found', }; return res.send(content); }) .catch(error => { let content = { data: error, success: false, message: 'Error while fetching Student Attendance.', }; return res.send(content); }); });
为什么原来的代码会报错?
- 直接对DATE类型字段用LIKE:PostgreSQL没有定义DATE和字符串之间的LIKE操作符,所以提示你需要显式类型转换;
- 给LIKE的值加了双引号:
"2018-01%"会被数据库解析成一个标识符(比如列名),而不是你想要匹配的字符串值,这会进一步导致错误。
内容的提问来源于stack exchange,提问作者Apurv Chaudhary
相关产品推荐
相关产品推荐

