MySQL 查询总订单量和总销售金额与当天的订单量和当天的销售金额
一、平常使用MySQL查询的话,都是这样写的语句://查询总订单量与总销售金额select count(id) as order_nums,sum(price) as order_price from order//查询当天订单量与当天销售金额select count(id) as day_nums,sum(price) as day_price from order where time >
·
一、平常使用MySQL查询的话,都是这样写的语句:
//查询总订单量与总销售金额
select count(id) as order_nums,sum(price) as order_price from order
//查询当天订单量与当天销售金额
select count(id) as day_nums,sum(price) as day_price from order where time >= '2021-10-01 00:00:00' and time <= '2021-10-02 00:00:00'
//或者
select count(id) as day_nums,sum(price) as day_price from order where DATE_FORMAT(time,'%Y-%m-%d') = '2021-10-01'
这样的话,会产生两次与MySQL的交互,查询时间会加长。
二、用一条语句来完成查询,这样与MySQL交互只有一次,就减少了与MySQL一次的交互;节约一次交互的时间。
//查询总订单量和总销售金额,与当天的订单量和当天的销售金额
select count(id) as order_nums,sum(price) as order_price,sum(IF(DATE_FORMAT(time,'%Y-%m-%d') = '2021-10-01',price,NULL)) as day_price,count(IF(DATE_FORMAT(time,'%Y-%m-%d') = '2021-10-01',id,NULL)) as day_nums from order
DATE_FORMAT : MySQL表中,时间字段类型为日期格式(2021-10-01)的使用这个函数。
FROM_UNIXTIME:MySQL表中,时间字段类型为 int 时间戳的使用这个函数。
如果你有更优的SQL语句,可以在下方评论喔!
更多推荐
已为社区贡献1条内容
所有评论(0)