node.js - mysql如何通過(guò)knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)
問(wèn)題描述
具體實(shí)現(xiàn)是要在product表中查詢出今天、七天和三十天內(nèi)的產(chǎn)品數(shù)量,具體的sql語(yǔ)句已經(jīng)寫好了
select sum(inputer as productNum) from `product` where to_days(`createdAt`)= to_days(now());
但是在knex.js里面我這樣寫根本不對(duì)
return knex(’product’) .where({ inputer: user, deletedAt: null }) .andWhere(’to_days(add_time)’, ’=’, ’to_days(now())’) .sum(’inputer as productNum’) .then(function (productRow) { return { product: productRow }; })
用having也不對(duì),knex文檔里沒(méi)有看到聚合函數(shù)的使用方法,求指教
return knex(’product’) .where({ inputer: user, deletedAt: null }) .groupBy(id) .having(’to_days(add_time)’, ’=’, ’to_days(now())’) .sum(’inputer as productNum’) .then(function (productRow) { return { product: productRow }; })
問(wèn)題解答
回答1:沒(méi)用過(guò)knex.js,但SQL好像復(fù)雜化了(原SQL會(huì)對(duì)createdAt字段進(jìn)行運(yùn)算,有可能會(huì)讓該字段的索引失效)。
SELECT sum(inputer) AS product_num FROM `product`WHERE createdAt >= ?
通過(guò)程序計(jì)算出今天、七天前和三十天前的起始時(shí)間(即yyyy-MM-dd 00:00:00),然后代入SQL即可。
相關(guān)文章:
1. golang - 用IDE看docker源碼時(shí)的小問(wèn)題2. html - css氣泡,實(shí)現(xiàn)“倒三角(不知道算不算三角了)”可透明的。3. 我何時(shí)應(yīng)該在Java中使用JFrame.add(component)和JFrame.getContentPane()。add(component)4. phpstudy8.1沒(méi)集成mysql-front5. 利用IPMI遠(yuǎn)程安裝centos報(bào)錯(cuò)!6. 運(yùn)行python程序時(shí)出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯(cuò)誤?7. docker - 如何修改運(yùn)行中容器的配置8. html5和Flash對(duì)抗是什么情況?9. javascript - 請(qǐng)指條明路,angular的$event,在select中卻是undefined?10. 前端 - @media query 使用出現(xiàn)的問(wèn)題?

網(wǎng)公網(wǎng)安備