MySQL中的循环可以通过使用循环控制语句来实现。MySQL支持以下几种类型的循环:
WHILE condition DO
statements;
END WHILE;
例如:
SET @counter = 0;
WHILE @counter < 10 DO
SET @counter = @counter + 1;
SELECT @counter;
END WHILE;
REPEAT
statements;
UNTIL condition;
END REPEAT;
例如:
SET @counter = 0;
REPEAT
SET @counter = @counter + 1;
SELECT @counter;
UNTIL @counter >= 10 END REPEAT;
loop_label: LOOP
statements;
IF condition THEN
LEAVE loop_label;
END IF;
END LOOP;
例如:
SET @counter = 0;
loop_label: LOOP
SET @counter = @counter + 1;
SELECT @counter;
IF @counter >= 10 THEN
LEAVE loop_label;
END IF;
END LOOP;
在循环内部可以执行任意的SQL语句,包括查询、插入、更新等操作。在循环过程中可以使用变量来进行计数、存储结果等操作。