while循环mysql_错误

时间:2014-07-29 15:37:07

标签: mysql loops

我是mysql循环的新手。我正在尝试创建第一个简单的循环,但它给了我一个错误消息(我们有mysqlyog,它没有显示有用的注释,所以我不知道我做错了什么)。这是我的代码:

SET @t1='2014-05-01';
SET @w=0;
WHILE @w<2 DO

SELECT COUNT(user_id), LEFT(@t1,7) AS mes_start_post 
FROM `user_activation` 
WHERE FROM_UNIXTIME(1st_net)>=@t1 
;
SET @w = @w + 1;
END WHILE;

消息是:

5 queries executed, 3 success, 2 errors, 0 warnings

--------------------------------------------------

Query: while @w<2 do SELECT count(user_id), LEFT(@t1,7) AS mes_start_post FROM `user_activation` WHERE FROM_UNIXTIME(1st_net)>=@t1

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'while @w<2 do
SELECT count(user_id), LEFT(@t1,7) AS mes_start_post 
FROM `user_a' at line 1

--------------------------------------------------
 Query: END while

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'END while' at line 1

当然我不知道错误是什么。

谢谢!

更新 我发布了很简单,但我真正需要的是那样的:

SET @t1='2014-05-01';
SET @d1=30;

WHILE @d1<DATEDIFF(@t1, NOW()) DO

SELECT user_id, LEFT(@t1,7) AS mes_start_post
FROM `user_activation` 
WHERE FROM_UNIXTIME(1st_net)>=@t1 
AND FROM_UNIXTIME(1st_net)<=DATE_ADD(@t1, INTERVAL @d1 DAY)

SET @d1 = @d1 + 30;
SET @t1 = dateadd(@t1, INTERVAL  30 DAY);

END WHILE;

1 个答案:

答案 0 :(得分:-1)

您可以使用返回与迭代次数一样多的行的子查询来代替循环:

SELECT count, mes_start_post
FROM (
    SELECT COUNT(user_id) AS count, LEFT(@t1,7) AS mes_start_post 
    FROM `user_activation` 
    WHERE FROM_UNIXTIME(1st_net)>=@t1) AS subq1
JOIN (SELECT 0
      UNION
      SELECT 1) AS subq2