具有MIN和MAX的GROUP BY - 属于解决方案的日期范围

时间:2016-08-21 07:01:52

标签: mysql group-by exists

我有以下数据表:

表1:

id  name    race_type        start_time              end_time
---     ----      ---------        ----------              --------
111 Phelps   Relay       2016-08-20 00:01:00           NULL
111 Phelps   Relay             NULL             2016-08-20 00:02:00
222 Phelps   Relay       2016-08-20 00:03:00           NULL
222 Phelps   Relay             NULL             2016-08-20 00:04:00
333 Lochte  Butterfly    2016-08-20 00:05:00           NULL
333 Lochte  Butterfly          NULL             2016-08-20 00:06:00
444 Lochte  Butterfly    2016-08-20 00:07:00           NULL
444 Lochte    Butterfly          NULL             2016-08-20 00:08:00

表2:

name      race_type        current_time       qualifies
----      ---------        ------------       ---------
Phelps      Relay       2016-08-20 00:03:30    
Lochte    Butterfly     2016-08-20 00:05:30

对于Table2中的两个事务,我需要确定这些事务的CURRENT_TIME是否属于Table1记录的START_TIME和END_TIME,与每个唯一ID配对,名称和race_type有关。

我想的是首先使用带有MIN和MAX函数的GROUP BY“合并”表1中的数据(id):

SELECT id,name,race_type, MIN(start_time) AS start_time, MAX(end_time) AS end_time
FROM Table1
GROUP BY id

这会给我以下结果:

+-----+--------+---------------+----------------------+---------------------+
| id  | name   |  race_type    |    start_time        |    end_time         |
+-----+--------+---------------+----------------------+---------------------|
| 111 | phelps |   relay       | 2016-08-20 00:01:00  | 2016-08-20 00:02:00 |
| 222 | phelps |   relay       | 2016-08-20 00:03:00  | 2016-08-20 00:04:00 |
| 333 | lochte |   Butterfly   | 2016-08-20 00:05:00  | 2016-08-20 00:06:00 |
| 444 | lochte |   Butterfly   | 2016-08-20 00:06:00  | 2016-08-20 00:08:00 |
+-----+--------+---------------+----------------------+---------------------+

基于这些结果,我可以更容易地确定他们的中继或蝴蝶游泳的phelps或lochte current_time(在表2中)是否处于各自名称和race_type的开始或结束时间范围中。如果它确实属于这些范围之一,我会将Table2 qualifies参数设置为true。

有人可以推荐可以完成此任务的MySQL查询吗?我猜我可以使用GROUP BY的某种组合来首先“合并”表1中的id,而不是使用exists

2 个答案:

答案 0 :(得分:1)

您可以使用inner join来获取当前时间介于该范围之间的所有结果:

SELECT * FROM (
SELECT id,name,race_type, MIN(start_time) AS start_time, MAX(end_time) AS end_time
FROM Table1
GROUP BY id
) AS results INNER JOIN table2 ON 
  results.name = Table2.name 
  AND results.type = Table2.type 
  AND Table2.current_time BETWEEN results.start_time AND results.end_time;

答案 1 :(得分:0)

有两种方法可以用两个nestet GROUP BY子查询做你想要的,但在你的情况下我更喜欢这个:

update Table2 t2
set qualifies = exists(
    select 1
    from Table1 t1a
    join Table1 t1b using(name, race_type, id)
    where t1a.name      = t2.name
      and t1a.race_type = t2.race_type
      and t1a.start_time <= t2.current_time
      and t1b.end_time   >= t2.current_time
);

sqlfiddle