比较两列:<= 不起作用,但 >= 起作用
Comparing two columns: <= does not work, but >= does
我想要 select 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 })
})
})
结果:
[]
如您所见,它是空的!
如果我使用大于或等于:
.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,} ]
这是为什么?
问题是,SQL 是这样工作的,但 Knex 不是! Knex 本质上是将 column1
的值与 字符串 'column2' 进行比较。所以,就好像我们 运行 SQL 查询:
SELECT * FROM items
WHERE column1 <= 'column2';
现在,在 MySQL(在我的示例中是 MariaDB)中,<=
比较整数与字符串 returns 0
(假)。但是,>=
比较 returns 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);
另请参阅:。
我想要 select 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 })
})
})
结果:
[]
如您所见,它是空的!
如果我使用大于或等于:
.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,} ]
这是为什么?
问题是,SQL 是这样工作的,但 Knex 不是! Knex 本质上是将 column1
的值与 字符串 'column2' 进行比较。所以,就好像我们 运行 SQL 查询:
SELECT * FROM items
WHERE column1 <= 'column2';
现在,在 MySQL(在我的示例中是 MariaDB)中,<=
比较整数与字符串 returns 0
(假)。但是,>=
比较 returns 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);
另请参阅: