SQL查询指南-结果重复

时间:2019-03-17 17:47:15

标签: php sql phpmyadmin

真的需要一些指导,我有一个网站,人们可以在其中上传图片到比赛中并获得结果(分数),我想拉出一个领导委员会,看看每个人的表现如何。但是我的SQL查询有重复的人名,有人可以告诉我在哪里更改我的查询,因此将说1个人参加3个比赛的结果加起来,并且输出中只列出了TOTAL标记。结果保存在tblMembEntComp fldResult中。

我目前正在得到什么:

Leadership Board

我的PHP代码:

<p><b>LEADERSHIP BOARD</b></p>
<?php
    $query = "SELECT `tblMember`.`fldFName`, `tblMember`.`fldSName`, `tblMembEntComp`.`fldResult` FROM `tblMember` AS `tblMember` JOIN `tblMembEntComp` as `tblMembEntComp` ON `tblMember`.`fldMemberID` = `tblMembEntComp`.`fldMemberID`ORDER BY `fldResult` DESC";

    $result = $conn -> query($query);

    while($row = $result -> fetch_assoc()) 
        {
            echo $row['fldFName']." ".$row['fldSName']." ".$row['fldResult']."<br>";
        } 
?>

更新: 我尝试了以下用户建议的GROUP BY函数,但是却抛出错误:

SQL Error

2 个答案:

答案 0 :(得分:1)

您似乎想要一个聚合查询。像这样:

SELECT m.fldSName, SUM(mec.fldResult) as fldResult
FROM tblMember m JOIN 
     tblMembEntComp mec
     ON m.fldMemberID =mec.fldMemberID
GROUP BY m.fldSName
ORDER BY SUM(mec.fldResult) DESC

答案 1 :(得分:0)

您应按tblMember主键对查询进行分组,如下所示:

<?php
    $query = "SELECT `tblMember`.`fldFName`, `tblMember`.`fldSName`, `tblMembEntComp`.`fldResult`, `tblMember`.`fldId` FROM `tblMember` AS `tblMember` JOIN `tblMembEntComp` as `tblMembEntComp` ON `tblMember`.`fldMemberID` = `tblMembEntComp`.`fldMemberID` GROUP BY `tblMember`.`fldId` ORDER BY `fldResult` DESC";

    $result = $conn -> query($query);

    while($row = $result -> fetch_assoc()) 
        {
            echo $row['fldFName']." ".$row['fldSName']." ".$row['fldResult']."<br>";
        } 
?>

您可以按字段更新分组作为您的主键。希望对您有帮助:)