一尘不染

PHP / MySQL的多个查询

mysql

<?php

$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";

$query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";

$query3 = "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)";

$query4 = "SELECT *, @rank_change = prev_rank - current_rank as rank_change from final_output";

$result = mysql_query($query4) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}

?>

所有查询都是独立工作的,但实际上很难将所有内容组合到一个结果中,因此我可以将其与mysql_fetch_array一起使用。

我试图创建视图以及临时表,但是每次它说表不存在或返回一个空的获取数组循环时……都有逻辑但语法混乱,我认为这是我第一次处理多个查询,我需要将所有查询合并在一起。期待获得支持。非常感谢。


阅读 397

收藏
2020-05-17

共1个答案

一尘不染

多亏了php.net,我提出了一个解决方案:您必须使用它(mysqli_multi_query($link, $query))来运行多个串联的查询。

 /* create sql connection*/
$link = mysqli_connect("server", "user", "password", "database");

$query = "SQL STATEMENTS;"; /*  first query : Notice the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS"; /* last query : Notice the dot before = at the end ! */

/* Execute queries */

if (mysqli_multi_query($link, $query)) {
do {
    /* store first result set */
    if ($result = mysqli_store_result($link)) {
        while ($row = mysqli_fetch_array($result))

/* print your results */    
{
echo $row['column1'];
echo $row['column2'];
}
mysqli_free_result($result);
}   
} while (mysqli_next_result($link));
}
2020-05-17