簡體   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