在 PHP/MySQL 中执行多个查询
问题:
执行多个独立查询并使用 PHP 和 MySQL 将结果组合成一个单一的、有凝聚力的结果可以构成挑战。
解决方案:
1. mysqli_multi_query()
示例:
// 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 }
2。单独的查询
示例:
// 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中文网其他相关文章!