PHP MySql查询获取每个用户的总和

时间:2018-11-27 23:07:13

标签: php mysql sql join

我的用户具有评分,我想显示每个用户的评分总额。我有2个表格:用户和反馈。我在USERS表中有4个用户。在表FEEDBACK(由applicant_id和app_experience列组成)中,我具有每个用户的评分。但是,我对每个人都有几个评分。

  $sql4 = "
 SELECT SUM(app_experience) as app_experience
     , applicant_id 
  FROM feedback f
  JOIN users u
    ON u.id=f.applicant_id 
 GROUP 
    BY feedback.applicant_id
";
  $res4 = mysqli_query($db,$sql4) or die(mysqli_error($db)); 

这是我的输出,但是只打印2个用户,因为在表FEEDBACK中,2个用户还没有任何反馈:

  foreach ($res4 as $row) 
  {
   echo "".$row['applicant_id']."----".$row['app_experience']."";
   echo "<br>";
  }

我的问题是如何输出所有4个用户,我想在每个用户旁边显示评分总数。

我正在做这样的事情,但是我不知道在下面的代码中在上面添加foreach循环的位置。你有什么想法吗?:

 $sql2 = "SELECT * FROM users";
 $res2 = mysqli_query($db,$sql2) or die(mysqli_error($db));
 while($row2 = mysqli_fetch_assoc($res2))
 {
   $id = $row2['id'];
   $name = $row2['name'];
 }

3 个答案:

答案 0 :(得分:1)

您只需要修改以下语句:

$sql4 = "SELECT SUM(app_experience) as app_experience, applicant_id FROM feedback INNER JOIN users ON users.id=feedback.applicant_id GROUP BY feedback.applicant_id";

至:

$sql4 = "SELECT COALESCE(SUM(app_experience), 0) as app_experience, applicant_id FROM users LEFT JOIN feedback ON users.id=feedback.applicant_id GROUP BY users.id";

users LEFT JOIN feedback ...子句将允许查询返回行,即使对于尚未反馈的用户也是如此。

当用户没有反馈时,COALESCE(SUM(app_experience), 0)的评估结果为0

使用此解决方案,您无需循环。

答案 1 :(得分:0)

SELECT users.*, (SELECT SUM(app_experience) FROM feedback WHERE applicant_id = users.id) as feedback FROM users

通过简短的SQL选择所有用户及其反馈

答案 2 :(得分:0)

按照书面规定,您的查询将不会运行。 GROUP BY子句引用了feedback,但是该引用已被别名更改为f

您似乎想要LEFT JOIN

SELECT u.id, SUM(f.app_experience) as app_experience
FROM feedback f LEFT JOIN
     users u
     ON u.id = f.applicant_id 
GROUP BY u.id;

这将为NULL返回一个app_experience值。如果您想要一个值(例如0),请使用COALESCE(SUM(f.app_experience), 0)