【问题标题】:Comparing two columns: <= does not work, but >= does比较两列:<= 无效,但 >= 有效
【发布时间】:2019-10-08 09:35:54
【问题描述】:

我想选择小于或等于column2column1 数据。然而,当我尝试使用&lt;= 时,我得到一个空结果,尽管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 })
  })
})

结果:

[]

如你所见,它是空的!

如果我使用大于或等于:

 .where('column1', '>=', 'column2')

我得到了所有的行:

[ RowDataPacket {
    column_id: 1,
    column1: 99,
    column2: 10, },
  RowDataPacket {
    column_id: 2,
    column1: 10,
    column2: 10, },
  RowDataPacket {
    column_id: 3,
    column1: 29,
    column2: 12,} ]

这是为什么?

【问题讨论】:

  • 你能检查/记录从 knex 返回的查询吗?

标签: mysql knex.js


【解决方案1】:

问题是,SQL 以这种方式工作,但 Knex 却不行! Knex 本质上是将column1 的值与字符串 'column2' 进行比较。所以,就好像我们运行了 SQL 查询:

SELECT * FROM items
    WHERE column1 <= 'column2';

现在,在 MySQL(在我的示例中为 MariaDB)中,整数与字符串的 &lt;= 比较返回 0(假)。但是,&gt;= 比较返回 1,这解释了您所看到的令人困惑的结果。其他一些数据库会显示错误(例如 Postgres):

postgres=# SELECT 1 <= 'foo';
ERROR:  invalid input syntax for integer: "foo"
LINE 1: SELECT 1 <= 'foo';                   ^

但 MariaDB 会让你侥幸逃脱:

MariaDB [(none)]> SELECT 1 <= 'foo';
+------------+
| 1 <= 'foo' |
+------------+
|          0 |
+------------+
1 row in set (0.000 sec)

MariaDB [(none)]> SELECT 1 >= 'foo';
+------------+
| 1 >= 'foo' |
+------------+
|          1 |
+------------+
1 row in set (0.000 sec)

要解决这个问题,您需要告诉 Knex 您实际上想要比较右侧的列值,而不是字符串。您可以使用knex.ref 完成此操作。试试这个:

db("items")
  .where("column1", "<=", db.ref("column2"))
  .then(console.log)
  .catch(console.error);

另请参阅:With knexjs, how do I compare two columns in the .where() function?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多