在 PHP/MySQL 中对综合数据执行多个查询
在处理复杂的数据分析时,在 PHP/MySQL 中运行多个查询可以提供无缝的解决方案。然而,连接多个查询并手动获取结果可能具有挑战性。本文探讨了一种使用 mysqli_multi_query($link, $query) 一次执行多个查询的技术。
考虑以下代码片段:
$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";
此代码执行一系列查询创建视图并选择数据。但是,要使用 mysql_fetch_array 获取结果,查询需要作为一个串联查询来执行。
使用 mysqli_multi_query
mysqli_multi_query 函数允许您执行多个串联查询在一次操作中。为此,您需要:
mysqli_multi_query 示例:
$link = mysqli_connect("server", "user", "password", "database"); $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"; if (mysqli_multi_query($link, $query)) { do { if ($result = mysqli_store_result($link)) { while ($row = mysqli_fetch_array($result)) { echo $row['player'] . $row['current_rank'] . $row['prev_rank'] . $row['rank_change']; } mysqli_free_result($result); } } while (mysqli_next_result($link)); }
替代方法:单独执行查询
单独执行查询可以让您控制执行顺序并使用临时表。要单独执行查询,您可以使用:
$query1 = "Create temporary table A select c1 from t1"; $result1 = mysqli_query($link, $query1) or die(mysqli_error()); $query2 = "select c1 from A"; $result2 = mysqli_query($link, $query2) or die(mysqli_error()); while ($row = mysqli_fetch_array($result2)) { echo $row['c1']; }
此方法需要您创建临时表并运行其他查询以从中检索数据。
选择正确的方法取决于您的具体情况需要。如果您需要多个查询的单个结果集,mysqli_multi_query 是一个合适的选项。但是,如果您需要更大的灵活性和对执行顺序的控制,那么单独执行查询可能是首选。
以上是如何在PHP/MySQL中高效执行多个查询?的详细内容。更多信息请关注PHP中文网其他相关文章!