Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySql Query Get Sum Per User

Tags:

sql

join

php

mysql

I have users with rating and I want to show the total amount of rating of each user. I have 2 tables: users and feedback. I have 4 users in USERS table. And in table FEEDBACK (consists of applicant_id and app_experience columns) I have the rating of each user. But, I have several ratings for each person.

  $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)); 

This is my output, but it prints only 2 users, because in table FEEDBACK 2 of the users do not have any feedback yet:

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

My question is how to output all 4 users and I want to show the total number of rating next to each user.

I am doing something like this, but I do not know where to add the foreach loop above in the code below. Do you have any ideas?:

 $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'];
 }
like image 333
Kaloyan Avatar asked Jun 13 '26 12:06

Kaloyan


1 Answers

You just have to modify the below statement :

$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";

to :

$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";

The users LEFT JOIN feedback ... clause will allow the query to return a row even for users who do not have a feedback yet.

The COALESCE(SUM(app_experience), 0) will evaluate to 0 when a user has no feedback yet.

With this solution you don't need to loop.

like image 132
GMB Avatar answered Jun 15 '26 01:06

GMB