node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)
問題描述
具體實現(xiàn)是要在product表中查詢出今天、七天和三十天內(nèi)的產(chǎn)品數(shù)量,具體的sql語句已經(jīng)寫好了
select sum(inputer as productNum) from `product` where to_days(`createdAt`)= to_days(now());
但是在knex.js里面我這樣寫根本不對
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也不對,knex文檔里沒有看到聚合函數(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 }; })
問題解答
回答1:沒用過knex.js,但SQL好像復(fù)雜化了(原SQL會對createdAt字段進行運算,有可能會讓該字段的索引失效)。
SELECT sum(inputer) AS product_num FROM `product`WHERE createdAt >= ?
通過程序計算出今天、七天前和三十天前的起始時間(即yyyy-MM-dd 00:00:00),然后代入SQL即可。
相關(guān)文章:
1. 數(shù)據(jù)庫 - mysql boolean型無法插入true2. .......3. node.js - 在搭建vue.js時,安裝淘寶npm鏡像cnpm,報錯,如何解決呢4. 視頻 - html5 video的autoplay 在智能手機上不運作?5. javascript - jquery選擇的dom元素如何更新?6. python - Django問題 ’WSGIRequest’ object has no attribute ’user’7. python - scrapy中返回函數(shù)的返回值8. javascript - H5頁面無縫輪播9. mysql輸入賬號密碼后跳出一大堆內(nèi)容后但卻進不了mysql?10. mysql服務(wù)無法啟動1067錯誤,誰知道正確的解決方法?
