如何关联两个没有通过密钥直接连接的mysql表

时间:2016-09-20 15:45:04

标签: mysql

我有以下两个mysql表。

表名:分析

id   execution_time
---  --------------
A1   1
A2   20
A3   35

表名:错误

bug_id creation_time
------ -------------
1000   1.1
1001   1.3
1002   20.2
1003   20.7
1004   20.9
1005   35.1

为Analysis A1

创建了错误1000,1001

为分析A2

创建了错误1002,1003,1004

为Analysis A3创建了错误1005

因此,Bug creation_time总是大于其Analysis的execution_time,而bug_creation_time总是小于后面分析的执行。

现在,1)如果我有分析ID,我怎么能找到相关的bug(bug_id)。

2)如何找到给定错误数据(id,creation_time)的相关分析ID

1 个答案:

答案 0 :(得分:3)

<强> 1) SQL FIDDLE DEMO

SELECT b.*, t.*
FROM Bugs b
CROSS JOIN (  SELECT a1.id, 
                     a1.`execution_time` as `start_time`, 
                     a2.`execution_time` as `end_time`
              FROM Analysis a1
              LEFT JOIN Analysis a2
                 ON a1.`execution_time` < a2.`execution_time`  
              WHERE a2.`execution_time` IS NULL
                 OR a2.`execution_time`  = (SELECT min( z.`execution_time`)
                                            FROM Analysis z
                                            WHERE z.`execution_time` > a1.`execution_time`)
            ) t
WHERE b.`creation_time` between `start_time` and `end_time`
   or (b.`creation_time` > `start_time` and `end_time` IS NULL)

OUTPUT: 只需要按ID过滤

enter image description here

<强> 2)

SELECT *
FROM Analysis a
WHERE a.id = (  SELECT MAX(id)
                FROM Analysis a
                WHERE a.execution_time < @bugCreationTime)