在PHP/MySQL 中執行多個查詢
問題:
問題:執行多個🎜>執行多個🎜>執行多個🎜>執行多個🎜>執行多個🎜>執行多個🎜>執行多個🎜>。獨立查詢並使用PHP 和MySQL 將結果組合成一個單一的、有凝聚力的結果可以構成挑戰。
解:
循環每個結果集,取得數據,並執行任何必要的處理。
// establish MySQL connection $link = mysqli_connect("server", "user", "password", "database"); // define multiple queries $query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X;"; $query .= "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH);"; $query .= "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank ON (current_rankings.player = previous_rankings.player);"; $query .= "SELECT *, @rank_change = prev_rank - current_rank as rank_change from final_output;"; // execute multiple queries if (mysqli_multi_query($link, $query)) { // loop through each result set do { if ($result = mysqli_store_result($link)) { // fetch data from each result set while ($row = mysqli_fetch_array($result)) { // process the data... } // free result set memory mysqli_free_result($result); } } while (mysqli_next_result($link)); } else { // handle query execution error }
範例:
根據需求組合結果更遠正在處理。
// establish MySQL connection $link = mysqli_connect("server", "user", "password", "database"); // execute first query $query1 = "Create temporary table A select c1 from t1"; $result1 = mysqli_query($link, $query1) or die(mysqli_error()); // execute second query $query2 = "select c1 from A"; $result2 = mysqli_query($link, $query2) or die(mysqli_error()); // fetch data from second query while ($row = mysqli_fetch_array($result2)) { // process the data... }範例:
以上是如何在 PHP 中有效率地執行和組合多個 MySQL 查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!