1

我需要帮助创建特定查询,以下是我的存款表的示例,empId 是一个外键,它引用我的“用户”表的主键,即“用户 ID”注意:此处未显示用户表

  mysql> SELECT * FROM deposit
    -> ;
+------------+---------------+---------+-------------+-------------+-------------+-------+
|    CheckId | jobId         | payRate | jobLocation | hours       | date_paid   | empId |
+------------+---------------+---------+-------------+-------------+-------------+-------+
|       1512 | entertainment |      12 | store1      |       10.00 | 2013-03-02  |     1 |
|       1510 | entertainment |      12 | store1      |        8.00 | 2013-03-01  |     1 |
|       1507 | retail        |      10 | store1      |        8.00 | 2013-03-18  |     1 |
|       1506 | retail        |      10 | store1      |       20.00 | 2013-03-19  |     1 |
+------------+---------------+---------+-------------+-------------+-------------+-------+

我想要的是计算所有特定 jobId 所有小时的总和,在这种情况下,如果我正确地进行了查询,它将如下所示:

+---------------+---------------+---------+
| payID         | payRate       | hours   | 
+---------------+---------------+---------+
|  entertainment| 12            |      18 | 
|        retail | 10            |      28 | 
+---------------+---------------+---------+

在这种情况下,只有两个 jobId,但它可能有超过 2 个

这是我的查询,它只显示一个 payId,所以我需要帮助修复它

另请注意,电子邮件是我的用户表的一个属性

  <table>";
             $query = "SELECT jobId, payRate, SUM(hours) AS 'All_Hours'
                       FROM users INNER JOIN deposit ON userId = empId
                      WHERE users.email = '" . $_SESSION['email'] ."' 
                      GROUP BY jobId,payRate";

                      if (!$result) { //if the query failed
                          echo("Error, the query could not be executed: " .
                          mysqli_error($db) . "</p>");
                          mysqli_close($db); //close the database
                      } //by now we have made a successful query  
                      while ($row = mysqli_fetch_assoc($result)){
                      echo "<tr><td>" .$row['jobId'] . "</td>
                            <td>" .$row['payRate'] . "</td>
                            <td>" .$row['All_Hours'] . "</td>
                            </tr>";
                      }
              echo"</table>
4

2 回答 2

3

您忘记GROUP BY在查询中添加子句导致结果中只有一条记录,

SELECT jobId, payRate, SUM(hoursWorked) AS 'All_Hours'
FROM   users INNER JOIN paycheck ON userId = empId
WHERE  users.email = 'session_email_here' 
GROUP  BY jobId, payRate
于 2013-03-20T03:18:07.470 回答
0

在存款台上

SELECT jobId, payRate, sum(hours) FROM deposit
group by 1, 2

我还建议你让它更具关系性:jobId并且jobLocation需要移动到新表

于 2013-03-20T03:26:15.113 回答