2017-01-23 57 views
0

林具有這些表分貝的存儲過程:試圖寫有開始時間和結束時間

drop table if exists events1; 
create table if not exists events1(
    time_stamp   decimal(16,6),  
    message    char(90)  not null default 'defult message' 
); 

drop table if exists events2; 
create table if not exists events2(
    time_stamp   decimal(16,6),  
    message    char(90)  not null default 'defult message' 
); 

drop table if exists events3; 
create table if not exists events3(
    time_stamp   decimal(16,6),  
    message    char(90)  not null default 'defult message' 
); 

insert into events1 (time_stamp,message) values (1485193300,"a1"); 
insert into events1 (time_stamp,message) values (1485193600,"b1"); 
insert into events1 (time_stamp,message) values (1485193900,"c1"); 

insert into events2 (time_stamp,message) values (1485193300,"a1"); 
insert into events2 (time_stamp,message) values (1485193600,"b2"); 
insert into events2 (time_stamp,message) values (1485193900,"c3"); 

insert into events3 (time_stamp,message) values (1485193300,"a1"); 
insert into events3 (time_stamp,message) values (1485193600,"b2"); 
insert into events3 (time_stamp,message) values (1485193900,"c3"); 

我試圖建立一個存儲過程,有3個參數:

start_time (int) (in epoch) 
end_time (int) (in epoch) 
interval (int) (in epoch) 

我不希望這個程序會迭代start_time,步驟爲區間直到end_time,並在每次迭代時,根據步驟和時間間隔獲得三個表的並集。

類似:

DELIMITER // 
CREATE PROCEDURE get_events 
(IN start_time INT, 
IN end_time INT, 
IN interval INT, 
) 
BEGIN 
     while [ start_time <= end_time] 
      do 
      next_time = start_time + interval 
      select * 
      from events1 
      where start_time <= time_stamp and time_stamp <= next_time 

      union 

      select * 
      from events2 
      where start_time <= time_stamp and time_stamp <= next_time 

      union 

      select * 
      from events3 
      where start_time <= time_stamp and time_stamp <= next_time 

      start_time = start_time + interval 


     end while 

END // 
DELIMITER ; 

我知道我有語法錯誤,我不知道我怎樣才能返回結果,並在WHERE情況下給定的時間間隔遍歷3代表的聯合。

請指教。

+0

你所說的「返回結果」是什麼意思? 'UNION'將爲WHILE每次迭代返回一個結果集。 –

回答

0

什麼是語法錯誤?

[是無效的語法;或許(WHILE

a = a + b是無效的語法;請參閱SET命令。

具有相同模式的3個表格是通常是一個糟糕的設計。

使用CHAR而不是VARCHAR我們通常是一個壞主意。

+0

我寫了架構只是爲了說明。我被困在存儲過程中。我把它們寫成僞代碼的時候,我不知道如何保存每個迭代的查詢結果,以及如何返回所有結果。 –

0
INSERT INTO "table name" 
select * 
    from events1 
    where start_time <= time_stamp and time_stamp <= next_time 

    union 

    select * 
    from events2 
    where start_time <= time_stamp and time_stamp <= next_time 

    union 

    select * 
    from events3 
    where start_time <= time_stamp and time_stamp <= next_time 

這會將查詢存儲在一個表中,然後您可以遍歷該表。不知道這是你要求的。

下面是文檔: https://dev.mysql.com/doc/refman/5.7/en/insert-select.html

相關問題