GROUP BY with MIN 和 MAX - 落在解决方案的日期范围内

GROUP BY with MIN and MAX - Fall within date range of solution

我有以下数据表:

Table1:

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

Table2:

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是否属于[=40=的START_TIME和END_TIME ]1 条关于每个唯一 ID 配对、名称和 race_type.

的记录

我在想的是首先 "merge" Table1 中的数据 (id) 使用带有 MIN 和 MAX 函数的 GROUP BY:

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 的接力或蝶泳(在 Table2 中)是否在他们的开始或结束时间范围内各自的名字和 race_type。如果它确实属于这些范围之一,我会将 Table2 限定参数设置为 true。

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

您可以使用 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;

有很多方法可以用两个嵌套的 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