使用SELECT和UNION的MySQL LOOP

时间:2019-07-18 15:20:09

标签: mysql select union

我的SQL查询有类似的问题。 Convert UNION selects to single select with loop in MySQL

我有“复杂的” SELECT,并且我将所有SELECT都合并了。

我的问题是,也许可以在LOOP中完成?

  label1: LOOP
    SET p1 = p1 + 1;
    IF p1 < 30 THEN

      SELECT //my select
      UNION ALL

      ITERATE label1;
    END IF;
    LEAVE label1;
  END LOOP label1;

您能告诉我它是否会以这种方式工作?我尝试编写带有定期事件的日历,并且希望逐个日期迭代日期(例如7天)并从SELECT收集结果

谢谢您!

1 个答案:

答案 0 :(得分:0)

嗨,我只用ID字段创建了DAY表,我将此表填充为1到366。现在,当我想进行7天迭代时,我正在这样做:

SET @date := '2014-06-26';
SELECT *, @date := DATE_ADD(@date, INTERVAL T.id DAY ) AS it_date

FROM (

MY SELECT how to use @date variable? it is always set to '2014-06-26', but in results I can see it is incremented
for example when I write

SELECT EV.*, @date I have got the same date '2014-06-26' not incremented but 'it_date' field is incremented

) AS T WHERE T.id <= 7 //For 7 days 

如何在子选择中使用变量?