2014-09-23 50 views
0
error_tbl     success_tbl 
id | creationTime   id|creationTime 
1 2014-09-23 10:03:40 1212 2014-09-23 10:02:40 
          1213 2014-09-23 10:03:40 
          1214 2014-09-23 10:10:40 

查詢的運行之後,我想有這樣的:MySQL的選擇與時間範圍和條件

result table 
creationTime  | fail_ids | succ_ids 
2014-09-23 10:03:40, 1,   NULL 
2014-09-23 10:02:40, NULL,  1212 
2014-09-23 10:03:40, NULL,  1213 

我想要的每個時間範圍內選擇的所有數據(成功和失敗)和每5分鐘只有在該時間段內有任何記錄存在於error_tbl中。

(SELECT 
    creationTime, 
    id as fail_ids,null as succ_ids 
FROM error_tbl a 

UNION 
SELECT 
    creationTime, 
    null as fail_ids ,id as succ_ids 
FROM success_tbl b 
) s 
+0

」只有當error_tbl中存在任何記錄「=>'WHERE EXISTS(SELECT something FROM error_tbl WHERE ...)' – DanFromGermany 2014-09-23 12:45:26

回答

0

鑑於簡化的模式,只需稍作更改以使其看起來乾淨整潔。

CREATE TABLE error(
    `error_id` INT, 
    `creation_time` DATETIME 
); 
INSERT INTO error(`error_id`, `creation_time`) VALUES 
    (1, '2014-09-23 10:03:40'), 
    (2, '2014-09-23 10:04:05'), 
    (3, '2014-09-24 10:08:04'); 

CREATE TABLE success(
    `success_id` INT, 
    `creation_time` DATETIME 
); 
INSERT INTO success(`success_id`, `creation_time`) VALUES 
    (1212, '2014-09-23 10:02:40'), 
    (1213, '2014-09-23 10:03:40'), 
    (1214, '2014-09-23 10:10:40'); 

這應該有效,但我不認爲它在大數據集上表現良好。

SELECT CONCAT(
    DATE_FORMAT(creation_time, '%Y-%m-%d %k:'), 
    LPAD(FLOOR(MINUTE(creation_time)/5) * 5, 2, 0), 
    ':00' 
) `creation_time`, 
    GROUP_CONCAT(error_id) `error_ids`, 
    GROUP_CONCAT(success_id) `success_ids` 
FROM (
    (
    SELECT NULL success_id, error_id, creation_time 
    FROM error 
) 
    UNION 
    (
    SELECT success_id, NULL error_id, creation_time 
    FROM success 
) 
) un 
GROUP BY FLOOR(UNIX_TIMESTAMP(creation_time)/(5 * 60)) 
HAVING error_ids IS NOT NULL 

SQL Fiddle snippet。 「

+0

我想要的結果表 – tugce 2014-09-23 12:15:11

+0

@tugce哦,這是一個不同的問題。我已經調整了答案,看看。 – saaj 2014-09-23 12:41:15

+0

非常感謝您的幫助,但是,我需要結果表,因爲我指定(creationTime是重要的)。性能不成問題,但如果發生任何錯誤,則需要查看5分鐘內的所有記錄集。 – tugce 2014-09-23 12:47:46