成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)

瀏覽:122日期:2022-06-20 17:05:10

問題描述

具體實(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里面我這樣寫根本不對(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文檔里沒有看到聚合函數(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會(huì)對(duì)createdAt字段進(jìn)行運(yùn)算,有可能會(huì)讓該字段的索引失效)。

SELECT sum(inputer) AS product_num FROM `product`WHERE createdAt >= ?

通過程序計(jì)算出今天、七天前和三十天前的起始時(shí)間(即yyyy-MM-dd 00:00:00),然后代入SQL即可。

相關(guān)文章: