[英]Loop through SQL and calculate sum in PHP
I have an issue with my code. 我的代码有问题。 I have 2 tables. 我有2张桌子。 First employee_id: 第一个employee_id:
|Employee id| |员工编号|
1 1个
2 2
3 3
And the second table called employee_times: 第二个表称为employee_times:
|Employee_id|Hours_dev|hours_pm| | Employee_id | Hours_dev | hours_pm |
|1|2|3| | 1 | 2 | 3 |
|1|3|4| | 1 | 3 | 4 |
|2|3|3| | 2 | 3 | 3 |
What I am trying to do is to calculate the total time that each employee has worked (hours_dev+hours_pm). 我要做的是计算每个员工的总工作时间(hours_dev + hours_pm)。 For example employee_id 1 has worked 12 hours 例如,employee_id 1工作了12个小时
So far I have tried to retrieve all the employee_id from the first table and use a for loop to go through the employee_times in an SQL statement (SEE CODE BELOW). 到目前为止,我已经尝试从第一个表中检索所有的employee_id,并使用for循环在SQL语句(请参见下面的代码)中遍历employee_times。 However the code does not work as it prints 0 for both employee_id and total_hours. 但是,该代码不起作用,因为它同时为employee_id和total_hours输出0。
I am using MYSQL on a localhost server. 我在本地服务器上使用MYSQL。
$sql = "SELECT employee_id FROM employee"; $ sql =“选择雇员的employee_id”; $result = mysql_query($sql); $ result = mysql_query($ sql); while($row = mysql_fetch_array) { $employee_id = $row['employee_id']; while($ row = mysql_fetch_array){$ employee_id = $ row ['employee_id']; } }
$employee_id_length = sizeof($employee_id);
for($i = 0; $i < $employee_id_length; $i++)
{
$sql4 = "SELECT employee_id, hours_dev, hours_pm FROM employee_times WHERE employee_id= '$employee_id[$i]'";
$result = mysql_query($sql4);
while($info = mysql_fetch_array($result));
{
$employee_id = $info['employee_id'];
$hours_dev=$info['hours_dev'];
$hours_pm=$info['hours_pm'];
$total_hours = ($total_hours + $hours_dev + $hours_pm );
}
//print "$employee_id worked for $total_hours";
}
Any help is much appreciated. 任何帮助深表感谢。
you can get sum directly 你可以直接得到总和
select employee_id, sum(hours_dev)+ sum(hours_pm) as total
from employee_times WHERE employee_id= '1'
group by employee_id
refer this Fiddle Demo 参考这个小提琴演示
this should get the data you need 这应该获得您需要的数据
SELECT
hours_dev,
hours_pm,
sum(hours_dev) + sum(hours_pm) as total_hours
FROM
employee_times
WHERE
employee_id = 123
GROUP BY
employee_id
This SQL query should pull the info much quicker than by script; 这个SQL查询应该比脚本更快地提取信息。
SELECT Employee_id, SUM(Hours_dev), SUM(Hours_pm), SUM(Hours_dev + Hours_pm)
FROM employee_times
GROUP BY Employee_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.