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中文網其他相關文章!

本文討論了使用MySQL的Alter Table語句修改表,包括添加/刪除列,重命名表/列以及更改列數據類型。

文章討論了為MySQL配置SSL/TLS加密,包括證書生成和驗證。主要問題是使用自簽名證書的安全含義。[角色計數:159]

文章討論了流行的MySQL GUI工具,例如MySQL Workbench和PhpMyAdmin,比較了它們對初學者和高級用戶的功能和適合性。[159個字符]

本文討論了使用Drop Table語句在MySQL中放下表,並強調了預防措施和風險。它強調,沒有備份,該動作是不可逆轉的,詳細介紹了恢復方法和潛在的生產環境危害。

本文討論了在PostgreSQL,MySQL和MongoDB等各個數據庫中的JSON列上創建索引,以增強查詢性能。它解釋了索引特定的JSON路徑的語法和好處,並列出了支持的數據庫系統。

文章討論了使用準備好的語句,輸入驗證和強密碼策略確保針對SQL注入和蠻力攻擊的MySQL。(159個字符)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver Mac版
視覺化網頁開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能