With knexjs, how do I compare two columns in the .where() function?

浪子不回头ぞ 提交于 2019-12-08 15:26:15

问题


Using knexjs only (no bookshelf) I would like to do something like the following query:

select * from table1 where column1 < column2

However, when I do this:

.table("table1").select().where("column1", "<", "column2")

The SQL that knexjs generates is:

select * from table1 where column1 < 'column2'

Which doesn't give the desired result b/c it's not comparing the value from the column, it's comparing the value of the string, 'column2'.

Anyone know how to do what I'm wanting? Thanks!


回答1:


Ok, so after some digging, it looks like it can be done this way. Not sure if this is best practice, but at the moment, it works so until I hear otherwise...

.table("table1").select().where("column1", "<", knex.raw("table1.column2"))

Again, not ideal, but it gets the job done. Just be sure to

import knex from "knex";

at the top of whatever file you're using this in.




回答2:


As of knex 0.15.0 (July 2018), we now have:

table("table1").select().where("column1", "<", knex.ref("column2"))

See https://knexjs.org/#Ref

As Greg Hornby mentions in the comment to the other answer, you can also use ?? in a raw query to bind to a column or table name.



来源:https://stackoverflow.com/questions/37447326/with-knexjs-how-do-i-compare-two-columns-in-the-where-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!