首页 > 解决方案 > 如何将带有别名的 SQL LEFT 放入书架?

问题描述

我需要这个SQL(在 mysql 控制台中完美运行):

SELECT LEFT(authors.last_name,1) AS first_char

"bookshelf.js".

当我走到这一步时:

let result = await qb.column('last_name').select().from('authors').as('first_char');

我无法得到

let result = await qb.column('last_name').select('LEFT(authors.last_name,1)').from('authors').as('first_char');

这个去。

它会导致以下错误:

Error: ER_BAD_FIELD_ERROR: Unknown column 'LEFT(authors.last_name,1)' in 'field list'

这对我来说没有意义,因为该列authors.last_name仍然存在。

标签: knex.jsbookshelf.js

解决方案


.select()防止 SQL 注入,因此您不能只是将随机 SQL 传递给它并期望它工作。您需要为此使用原始表达式:

qb.column('last_name').select(qb.raw('LEFT(authors.last_name,1)')).from('authors').as('first_char');

在这方面,从技术上讲,这不是一个书架问题,因为查询构建器只是 knex。


推荐阅读