node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)
問題描述
具體實(shí)現(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字段進(jìn)行運(yùn)算,有可能會讓該字段的索引失效)。
SELECT sum(inputer) AS product_num FROM `product`WHERE createdAt >= ?
通過程序計(jì)算出今天、七天前和三十天前的起始時(shí)間(即yyyy-MM-dd 00:00:00),然后代入SQL即可。
相關(guān)文章:
1. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?2. 請教各位大佬,瀏覽器點(diǎn) 提交實(shí)例為什么沒有反應(yīng)3. javascript - 微信小程序封裝定位問題(封裝異步并可能多次請求)4. javascript - 移動端textarea不能上下滑動,該怎么解決?5. 網(wǎng)頁爬蟲 - 用Python3的requests庫模擬登陸B(tài)ilibili總是提示驗(yàn)證碼錯誤怎么辦?6. javascript - 關(guān)于audio標(biāo)簽暫停的問題7. css - 對于類選擇器使用的問題8. 大家好,請問在python腳本中怎么用virtualenv激活指定的環(huán)境?9. javascript - Web微信聊天輸入框解決方案10. Matlab和Python編程相似嗎,有兩種都學(xué)過的人可以說說嗎
