为什么在Node.js和mysql / knex.js中的两列之间不起作用,但是要起作用?
我想要获取/获取column1数据,该数据小于或等于column2,但是我得到空结果。但是我已经在column1中有一个小于column2的数据。
让我显示我的代码:
router.get('/', function(req, res, next) {
db('items').select().where('column1', '<=', 'column2').then((notify)=>{
console.log(notify)
res.render('index', { title: 'Express', notify:notify })
})
})
以及控制台日志中的结果:
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
[]
如您所见,结果为空!
但是如果我使用更大或等于.where('column1', '>=', 'column2')
,则得到列1的全部数据:
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
[ RowDataPacket {
column_id: 1,
column1: 99,
column2: 10, },
RowDataPacket {
column_id: 2,
column1: 10,
column2: 10, },
RowDataPacket {
column_id: 3,
column1: 29,
column2: 12,} ]
所以,我如何只能获得更少或相等的数据?
回答如下:啊,我知道现在发生了什么。我的道歉:我实际上是让您误入了您先前问题的答案,我认为该问题可能已被删除。
问题是,SQL以这种方式工作,但是Knex不能! Knex本质上是将column1
的值与string'column2'进行比较。因此,就好像我们运行了SQL查询:
SELECT * FROM items
WHERE column1 <= 'column2'
[现在,在SQLite中,将整数与字符串进行<=
比较将返回true,在SQLite的情况下将返回1
。但是,=
或>=
比较返回false,这说明了您看到的令人困惑的结果。其他一些数据库将显示错误(例如Postgres):
postgres=# select 1 <= 'foo';
ERROR: invalid input syntax for integer: "foo"
LINE 1: select 1 <= 'foo'; ^
但是SQLite将让您摆脱它:
sqlite> SELECT 10 <= '20';
10 <= '20'
----------
1
或
sqlite> SELECT 20 >= '5';
20 >= '5'
----------
0
由于这个原因,我想您正在使用SQLite,因为它是Knex的默认开发数据库。
要解决此问题,您需要告诉Knex,您实际上是希望比较的右侧是列值,而不是字符串。您可以使用knex.ref
完成此操作。试试这个:
knex.ref