2011-04-14 60 views
0

考慮到下面的兩個表格,只顯示產品未處於離線狀態的活動時間。請記住,這是一小部分數據。活動表中有多個產品,離線表中有多個時間戳。SQL挑戰 - 使用多個參考日期進行中斷

目標是在產品上線時輸出。因此,根據以下數據,我需要一個將返回的查詢:第3,6,7行 - 這些是產品聯機時的時間戳。

mysql> select * from activity; 
+------------+---------------------+ 
| product_id | activity_date  | 
+------------+---------------------+ 
|   1 | 2011-04-13 12:00:00 | 
|   1 | 2011-04-13 01:00:00 | 
|   1 | 2011-04-13 02:00:00 | 
|   1 | 2011-04-13 03:00:00 | 
|   1 | 2011-04-13 04:00:00 | 
|   1 | 2011-04-13 05:00:00 | 
|   1 | 2011-04-13 06:00:00 | 
+------------+---------------------+ 
7 rows in set (0.01 sec) 

mysql> select * from offline 
+------------+---------------------+---------------------+ 
| product_id | offline_start  | offline_end   | 
+------------+---------------------+---------------------+ 
|   1 | 2011-04-13 12:00:00 | 2011-04-13 01:00:00 | 
|   1 | 2011-04-13 03:00:00 | 2011-04-13 04:00:00 | 
+------------+---------------------+---------------------+ 
2 rows in set (0.01 sec) 

回答

0
create table activity 
(
    product_id int, 
    activity_date datetime 
); 

create table [offline] 
(
    product_id int, 
    offline_start datetime, 
    offline_end datetime 
); 

insert into activity(product_id, activity_date) 
    values (1, '2011-04-13 12:00:00 AM') 
     ,(1, '2011-04-13 01:00:00 AM') 
     ,(1, '2011-04-13 02:00:00 AM') 
     ,(1, '2011-04-13 03:00:00 AM') 
     ,(1, '2011-04-13 04:00:00 AM') 
     ,(1, '2011-04-13 05:00:00 AM') 
     ,(1, '2011-04-13 06:00:00 AM'); 

insert into [offline](product_id, offline_start, offline_end) 
    values (1, '2011-04-13 12:00:00 AM', '2011-04-13 01:00:00 AM') 
     ,(1, '2011-04-13 03:00:00 AM', '2011-04-13 04:00:00 AM');   

select a.* 
from activity a 
     left join offline o 
      on a.product_id = o.product_id 
      and a.activity_date between o.offline_start and o.offline_end 
where o.product_id IS NULL 

不要有一個MySQL服務器設置在家裏測試,但如果AM不工作,然後12點爲00:00:00等活動表中的第一項應是

1, '2011-04-13 00:00:00' 

和離線表中的第一項應是

1, '2011-04-13 00:00:00', '2011-04-13 01:00:00' 

我的SQL服務器上測試這一點,這裏是輸出:

product_id activity_date 
1 2011-04-13 02:00:00.000 
1 2011-04-13 05:00:00.000 
1 2011-04-13 06:00:00.000 
+0

沒有效果......沒如何ü檢索'activity' – diEcho 2011-04-14 04:49:15

+0

@diecho其左外最後兩行聯接 – clyc 2011-04-14 04:58:28

+0

不要忘了添加索引到的product_id(2個),activity_date並在range_index( offline_start + offline_end)。 – Johan 2011-04-14 09:10:56