首頁 > 資料庫 > mysql教程 > 如何在 MySQL 中循環結果集?

如何在 MySQL 中循環結果集?

Patricia Arquette
發布: 2024-11-15 13:07:02
原創
965 人瀏覽過

How Can I Loop Through Result Sets in MySQL?

Looping Over Result Sets in MySQL

This article explores the concept of looping over result sets in MySQL, a fundamental operation in database programming. We aim to emulate the functionality of the following PHP code:

$result = mysql_query("SELECT something FROM somewhere WHERE some stuff");
while ($row = mysql_fetch_assoc($result)) {
    // check values of certain fields, decide to perform more queries, or not
    // tack it all into the returning result set
}
登入後複製

Cursor-Based Approach

MySQL provides cursors for iterating over result sets. However, it lacks capabilities like FOR EACH ROW syntax for trigger implementations. Despite this, it is possible to create a cursor-based loop using the following approach:

SET @S = 1;
LOOP
    SELECT * FROM somewhere WHERE some_conditions LIMIT @S, 1
    -- IF NO RESULTS THEN
    LEAVE
    -- DO SOMETHING
    SET @S = @S + 1;
END LOOP
登入後複製

Stored Procedure with Cursor

A more structured way to implement this logic is through a stored procedure that employs a cursor. Here is an example:

CREATE PROCEDURE GetFilteredData()
BEGIN
  DECLARE bDone INT;

  DECLARE var1 CHAR(16);    -- or approriate type
  DECLARE var2 INT;
  DECLARE var3 VARCHAR(50);
  
  DECLARE curs CURSOR FOR  SELECT something FROM somewhere WHERE some stuff;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;

  DROP TEMPORARY TABLE IF EXISTS tblResults;
  CREATE TEMPORARY TABLE IF NOT EXISTS tblResults  (
    --Fld1 type,
    --Fld2 type,
    --...
  );

  OPEN curs;

  SET bDone = 0;
  REPEAT
    FETCH curs INTO var1, var2, var3;

    IF whatever_filtering_desired
       -- here for whatever_transformation_may_be_desired
       INSERT INTO tblResults VALUES (var1, var2, var3);
    END IF;
  UNTIL bDone END REPEAT;

  CLOSE curs;
  SELECT * FROM tblResults;
END
登入後複製

Considerations

While cursors can be helpful for implementing complex business rules, they come with certain drawbacks. Therefore, it is recommended to consider alternative methods, such as expressing the desired transformations and filters in a single, declarative SQL query.

以上是如何在 MySQL 中循環結果集?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板