我的代码存在问题。我有2张桌子。第一个employee_id:
|员工ID |
1
2
3
第二个表名为employee_times:
| EMPLOYEE_ID | Hours_dev | hours_pm |
| 1 | 2 | 3 |
| 1 | 3 | 4 |
| 2 | 3 | 3 |
我要做的是计算每位员工的总工作时间(hours_dev + hours_pm)。例如,employee_id 1工作了12个小时
到目前为止,我已尝试从第一个表中检索所有employee_id,并使用for循环在SQL语句中查看employee_times(参见下面的代码)。但是代码不起作用,因为它为employee_id和total_hours打印0。
我在localhost服务器上使用MYSQL。
$ sql =“SELECT employee_id FROM employee”; $ result = mysql_query($ sql); 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";
}
非常感谢任何帮助。
答案 0 :(得分:1)
你可以直接得到总和
select employee_id, sum(hours_dev)+ sum(hours_pm) as total
from employee_times WHERE employee_id= '1'
group by employee_id
参考此Fiddle Demo
答案 1 :(得分:1)
这应该可以获得您需要的数据
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
答案 2 :(得分:1)
看一下聚合函数: http://www.w3schools.com/sql/sql_functions.asp http://www.w3schools.com/sql/sql_func_sum.asp
答案 3 :(得分:0)
此SQL查询应该比脚本更快地提取信息;
SELECT Employee_id, SUM(Hours_dev), SUM(Hours_pm), SUM(Hours_dev + Hours_pm)
FROM employee_times
GROUP BY Employee_id