需要通过更改参数来循环MySql查询

时间:2016-05-20 06:32:59

标签: mysql loops

我是mysql脚本的新手,我希望通过将00:00:00时间增加到30分钟来执行此查询。

类似这样的事情

Select count(*) 
FROM ctrdb.CTR_LINE_ITEM 
where LOAD_DATE BETWEEN '2016-05-18 00:00:00' AND '2016-05-18 00:30:00' 
order by load_date;

Select count(*) 
FROM ctrdb.CTR_LINE_ITEM 
where LOAD_DATE BETWEEN '2016-05-18 00:30:00' AND '2016-05-18 00:60:00' 
order by load_date;
你能帮我吗?

1 个答案:

答案 0 :(得分:1)

如果你想在mysql中实现这一点,并希望为每个查询获得单独的结果集 然后,您需要使用存储过程循环中运行查询。

在mysql http://www.mysqltutorial.org/stored-procedures-loop.aspx

中读取循环

或者没有多个查询,您也可以使用 union

    DELIMITER $$
CREATE PROCEDURE getdata()
 BEGIN
 DECLARE x  INT;

 DECLARE maximum INT; # you can use date as well
 DECLARE startdate  DATE;
 DECLARE enddate  DATE;

 SET x =0;

 SET maximum = 10;
 SET startdate =   '2016-05-18 00:00:00';


 loop_label:  LOOP
    IF  x > 10 THEN 
        LEAVE  loop_label;
    END  IF;
    SET  x = x + 1;
    SET enddate =   startdate   + INTERVAL 30 MINUTE;
    Select count(*) ,startdate
    FROM ctrdb.CTR_LINE_ITEM 
    where LOAD_DATE BETWEEN '2016-05-18 00:00:00' AND '2016-05-18 00:30:00' 
    order by load_date;
    SET startdate =   startdate   + INTERVAL 30 MINUTE;

END LOOP; 
END $$

DELIMITER ;