node.js - mysql如何通过knex查询今天和七天内的汇总数据
怪我咯
怪我咯 2017-04-17 14:59:44
0
1
787

具体实现是要在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)
PHPzhong

没用过knex.js,但SQL好像复杂化了(原SQL会对createdAt字段进行运算,有可能会让该字段的索引失效)。

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

通过程序计算出今天、七天前和三十天前的起始时间(即yyyy-MM-dd 00:00:00),然后代入SQL即可。

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!