首页 > 解决方案 > 将 SQL 查询转换为 KnexJS

问题描述

我正在尝试将 SQL 查询转换为 KnexJS 格式,但当前的 KnexJS 查询给了我以下错误。

这是原始查询和我一直在为 KnexJS 工作的查询。请更正我的 KnexJS 查询。

先感谢您!

原始 SQL 查询:

select count(distinct date) 
from task_history
where 
store_id = 100 and date >
(select date from (
select date, count(*) as count_all, count(case when finish_time is not null 
then 1 else null end) as count_finished
from task_history
where store_id = 100 
group by date
order by count_finished, date desc
fetch first row only) as get_max_date)

KnexJS 查询:

.table("task_history")
.count(db.raw("'distinct date'"))
.where('store_id', 100)
.where('date', '>', function() {
    this.select('date')
    .from(function() {
        this.select('date')
        .table("task_history")
        .first()
        .count('* as count_all')
        .count(db.raw(`case when finish_time is not null then 1 else null end as count_finished`))
        .where('store_id', 100)
        .groupBy('date')
        .orderBy('count_finished', 'desc')
        .orderBy('date', 'desc')
        .as('get_max_date')
    })
})

标签: sqlknex.js

解决方案


这是一个复杂的查询。由于您没有共享 SQL 结构供其他人尝试相同的查询,我建议您尝试在查询中包含此“调试”子句:

.on('query-error', function(ex, obj) {
    console.log("KNEX query-error ex:", ex, "obj:", obj);
})

这将在查询崩溃时为您输出生成的 SQL。这可能会告诉你陈述的哪一部分是不正确的。

祝你好运。


推荐阅读