MySql:Query仅返回选择的第一行

时间:2016-08-09 10:48:50

标签: php mysql sql mysqli

我创建了这段代码,但是当我运行它时会创建表但只有第一行,表格我得到的数据有多行,我需要插入完整的数据。一些帮助

<?php
include("conf.php");
$file_name = "testing2";
$table = "TEMP_".$file_name;
$table1 = "TEMP1_".$file_name;
$query = "CREATE TABLE IF NOT EXISTS $table1(Id INT AUTO_INCREMENT PRIMARY KEY)
CHARACTER SET utf8 COLLATE utf8_general_ci
SELECT Team, GamesPlayedHome, GoalsScorredHome, GoalsAcceptedHome, RedCardGotHome, AvarageGoalsScorredHome, AvarageGoalsAcceptedHome, GamesPlayedAway, GoalsScorredAway, GoalsAcceptedAway, RedCardGotAway, AvarageGoalsScorredAway, AvarageGoalsAcceptedAway, 
AvarageRedCardGotHome, AvarageRedCardGotAway, AvarageShotsOnTargedHome, AvarageShotsOnTargedAway,
AvarageGoalsScorredHome / avg(AvarageGoalsScorredHome) AS AttackingStrengthHome, AvarageGoalsAcceptedHome / avg(AvarageGoalsAcceptedHome) AS DefensiveStrengthHome,
AvarageGoalsScorredAway / avg(AvarageGoalsScorredAway) AS AttackingStrengthAway, AvarageGoalsAcceptedAway / avg(AvarageGoalsAcceptedAway) AS DefensiveStrengthAway 
FROM $table 
";
$data= mysqli_query($conn,$query) or die(mysqli_error($conn));
while($row = mysqli_fetch_assoc($data)){
    foreach($row as $cname => $cvalue){
        print "$cname: $cvalue\t";
    }
    print "\r\n";
}
?>

1 个答案:

答案 0 :(得分:2)

您的查询具有聚合函数(avg()),没有GROUP BY。但是,仅添加GROUP BY似乎并不正确。我想你想要这样的东西:

SELECT Team, GamesPlayedHome, GoalsScorredHome, GoalsAcceptedHome, 
       RedCardGotHome, AvarageGoalsScorredHome, AvarageGoalsAcceptedHome,
       GamesPlayedAway, GoalsScorredAway, GoalsAcceptedAway, RedCardGotAway,
       AvarageGoalsScorredAway, AvarageGoalsAcceptedAway, 
       AvarageRedCardGotHome, AvarageRedCardGotAway, AvarageShotsOnTargedHome, AvarageShotsOnTargedAway,
       AvarageGoalsScorredHome / tt.avg_AvarageGoalsScorredHome AS AttackingStrengthHome,
       AvarageGoalsAcceptedHome / tt.avg_AvarageGoalsAcceptedHome AS DefensiveStrengthHome,
       AvarageGoalsScorredAway / tt.avg_AvarageGoalsScorredAway AS AttackingStrengthAway,
       AvarageGoalsAcceptedAway / tt.avg_AvarageGoalsAcceptedAway AS DefensiveStrengthAway 
FROM $table t CROSS JOIN
     (SELECT avg(AvarageGoalsScorredHome) as avg_AvarageGoalsScorredHome,
             avg(AvarageGoalsAcceptedHome) as avg_AvarageGoalsAcceptedHome,
             avg(AvarageGoalsScorredAway) as avg_AvarageGoalsScorredAway,
             avg(AvarageGoalsAcceptedAway) as avg_AvarageGoalsAcceptedAway
      FROM $table tt
     ) tt;

注意:你应该正确拼写列名:“average”和“scored”是正确的拼写。