MySQL查询以使用日期范围获取数据

时间:2018-09-05 07:49:25

标签: php mysql sql mysql-workbench daterangepicker

此查询在MySql工作台中给出正确的结果-

SELECT tbl_visit_info.visitor_id,tbl_visit_info.retailer_id,tbl_retailer.retailer_shop_name,
  SUM( IF( tbl_visit_info.activity_type = 1 ,1,0)) AS feedback,
SUM( IF( tbl_visit_info.activity_type = 2 ,1,0)) AS promise_order,
SUM( IF( tbl_visit_info.activity_type = 3 ,1,0)) AS stock,
SUM( IF( tbl_visit_info.activity_type = 6 ,1,0)) AS payment,
tbl_visit_info.date as visit_date
FROM tbl_visit_info,tbl_retailer 
where tbl_visit_info.retailer_id=tbl_retailer.retailer_id 
and tbl_visit_info.visitor_id=80
group by visitor_id,retailer_id 
having date_format(tbl_visit_info.date, '%Y-%m-%d') BETWEEN '2018-07-01' AND '2018-09-02';

但是,当我想将变量代替80和日期范围作为变量传递时,它没有给出任何结果。查询是-

SELECT tbl_visit_info.visitor_id,tbl_visit_info.retailer_id,tbl_retailer.retailer_shop_name,
  SUM( IF( tbl_visit_info.activity_type = 1 ,1,0)) AS feedback,
  SUM( IF( tbl_visit_info.activity_type = 2 ,1,0)) AS promise_order,
  SUM( IF( tbl_visit_info.activity_type = 3 ,1,0)) AS stock,
  SUM( IF( tbl_visit_info.activity_type = 6 ,1,0)) AS payment
  FROM tbl_visit_info,tbl_retailer
  where tbl_visit_info.retailer_id=tbl_retailer.retailer_id
  and tbl_visit_info.visitor_id='".$_GET["sr_id"]."'
  group by visitor_id,retailer_id having date_format(date, '%Y-%m-%d') BETWEEN 
  '".$_GET["start_date"]."' AND '".$_GET["end_date"]."'"

当我用PHP编写代码时,此查询没有给出任何结果。

1 个答案:

答案 0 :(得分:0)

您应该在where子句中添加日期过滤器,而不要使用having:

SELECT tbl_visit_info.visitor_id,tbl_visit_info.retailer_id,tbl_retailer.retailer_shop_name,
  SUM( IF( tbl_visit_info.activity_type = 1 ,1,0)) AS feedback,
  SUM( IF( tbl_visit_info.activity_type = 2 ,1,0)) AS promise_order,
  SUM( IF( tbl_visit_info.activity_type = 3 ,1,0)) AS stock,
  SUM( IF( tbl_visit_info.activity_type = 6 ,1,0)) AS payment
  FROM tbl_visit_info,tbl_retailer
  where tbl_visit_info.retailer_id=tbl_retailer.retailer_id
  and tbl_visit_info.visitor_id='".$_GET["sr_id"]."' 
  and date_format(date, '%Y-%m-%d') BETWEEN 
  '".$_GET["start_date"]."' AND '".$_GET["end_date"]."'"
  group by visitor_id,retailer_id