node.js - mysql如何通過knex查詢今天和七天內的匯總數據
問題描述
具體實現是要在product表中查詢出今天、七天和三十天內的產品數量,具體的sql語句已經寫好了
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文檔里沒有看到聚合函數的使用方法,求指教
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好像復雜化了(原SQL會對createdAt字段進行運算,有可能會讓該字段的索引失效)。
SELECT sum(inputer) AS product_num FROM `product`WHERE createdAt >= ?
通過程序計算出今天、七天前和三十天前的起始時間(即yyyy-MM-dd 00:00:00),然后代入SQL即可。
相關文章:
1. css3 - css before 中文亂碼?2. javascript - 百度echarts series數據更新問題3. mysql - 一個表和多個表是多對多的關系,該怎么設計4. css - 求推薦幾款好用的移動端頁面布局調試工具呢?5. Mysql && Redis 并發問題6. javascript - node服務端渲染的困惑7. mysql新建字段時 timestamp NOT NULL DEFAULT ’0000-00-00 00:00:00’ 報錯8. php - 第三方支付平臺在很短時間內多次異步通知,訂單多次確認收款9. html5 - h5寫的app用的webview,用手機瀏覽器打開不顯示?10. javascript - webpack --hot 熱重載無效的問題
