2016-09-20 52 views
0

我有以下兩個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 

錯誤1000,1001用於分析A1

錯誤1002,1003,1004創建用於分析A2

爲分析A3創建了錯誤1005

因此,Bug creation_time始終大於其Analysis的execution_time,並且bug_creation_time始終小於後面分析的執行次數。

現在,1)我如何找到相關的錯誤(bug_id),因爲我有一個分析ID。

2)我怎麼能找到一個給定的錯誤數據(ID相關的分析ID,CREATION_TIME)

+0

爲什麼錯誤1004兩次在此表中存在嗎?爲什麼它會分析A3?你的邏輯沒有解釋自己。 –

+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:只需要過濾器通過編號

enter image description here

2)

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

如果分析的執行時間增加超過1,解決方案1)將不起作用。在那種情況下,1)將如何?非常感謝。 –

+0

是的,我看到你改變了你的問題。在它上面工作。那麼2)呢? –

+0

完成,檢查演示 –