繁体   English   中英

拆分日期范围并在mysql中获得组合结果

[英]Split date range and get combined results in mysql

我有两张桌子

orders_status_history

   id | order_id | status |   date 
   1  |  1201    |  2     | 2015-01-20
   2  |  1124    |  4     | 2015-02-01
   3  |  1245    |  1     | 2015-02-14
   4  |  1365    |  2     | 2015-03-10

saved_shipping_invoices

   id | order_id  | product_id |  date 
   1  |  1348     |  12541     | 2015-12-18
   2  |  1298     |  11485     | 2016-01-02
   3  |  1319     |  14521     | 2016-05-14
   4  |  1441     |  10124     | 2016-05-14

和一年的日期范围即

$start_date = '2015-09-30';
$end_date   = '2016-09-30';

表“shipping_invoice_history”中的数据从2015-12-18开始。 现在我想打破2015-12-18的日期间隔。 现在将有两个间隔

$interval1_start = '2015-09-30';
$interval_end    = '2015-12-17';

$interval2_start = '2015-12-18';
$interval2_end   = '2016-09-30';

当它打破日期间隔时,我想在第一个时间间隔从表“orders_status_history”获取数据,但是在第二个时间间隔,它从“shipping_invoice_history”获取数据。我还需要在单个表中显示数据。

  $week = '2015-09-30 @@ 2016-09-30';
     $week_ranges  = explode('@@', $week);
    if ($week_ranges[0] > '2015-12-18' )
                    {
                        $invoices_shipped_qty  = tep_db_query("SELECT  *  FROM `saved_shipping_invoices` WHERE `date_created` BETWEEN '".$week_ranges[0]."' AND '".$week_ranges[1]."'");
                        $invoices_shipped_arr = tep_db_fetch_array($invoices_shipped_qty);
                        $total_sent =  $invoices_shipped_arr['shiped_qty'];
                        }
                        else {  
                    $total_order_status_complete = tep_db_query("SELECT  *  FROM `orders_status_history` WHERE `orders_status_id` = '17'  AND `date_added` BETWEEN '".$week_ranges[0]." 00:00:00' AND '".$week_ranges[1]." 23;59:59'");
                    $total_order_status_complete_arr = tep_db_fetch_array($total_order_status_complete);

请建议我如何将日期间隔分成两部分,从两个表中获取结果并在单次运行中显示。

可能这就是你想要的

select 
  'order_status_history' as table, 
  id, 
  order_id, 
  status, 
  null as product_id, 
  date from order_status_history
where 
 date between '2015-09-30' and '2015-12-17'
union all
select 
  'saved_shipping_invoices' as table, 
  id,
  order_id,
  null as status, 
  product_id, 
  date 
from saved_shipping_invoices
 where 
  date between '2015-12-18' and '2016-09-30' 

根据查询的动态程度,我喜欢这样做而不是联合。

我更喜欢这个选项:

select 

if(date <='2015-12-17', 'Phase 1',
if(date >='2015-12-18', 'Phase 2', 
'None')), 

  id, 
  order_id, 
  status, 
  null as product_id, 
  date from order_status_history
where 
 date between '2015-09-30' and '2016-09-30'

要么

select 

if(date between '2015-09-30' and '2015-12-17', 'Phase 1',
if(date between '2015-12-18' and '2016-09-30', 'Phase 2', 
'None')), 

  id, 
  order_id, 
  status, 
  null as product_id, 
  date from order_status_history
where 
 date between '2015-09-30' and '2016-09-30'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM