sql challenge - 使用多个引用来进行中断日期

时间:2011-04-14 04:27:56

标签: mysql sql join

根据下面的2个表格,仅显示产品未脱机时的活动时间。请记住,这是一小部分数据。活动表中将有多个产品,脱机表中会有多个时间戳。

目标是在产品上线时输出。所以根据下面的数据,我需要一个将返回的查询:第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)

1 个答案:

答案 0 :(得分: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 server上测试了这个,这是输出:

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