如何从多个表中求和并避免使用笛卡尔积

时间:2019-01-16 20:19:59

标签: php mysql

我正在为使用php和phpmyadmin / sql的员工开发内部时钟系统。每天跟踪工作时间,午餐时间和咖啡时间。每个类别每天可以有多个条目。最后,我需要为任何给定的一周创建一个摘要报告。该报告来自phpmyadmin中的4个不同的表格,如下所示。

我尝试了很多事情,并搜索了很多地方。但是我不能超越笛卡尔积。

Tables:
Employee Table:

EmployeeID | First name | Last name |

Hours Table:

Clock ID  | Employee ID | ClockIN | Clock Out | Year | WeekID | Mon |...|Sun

auto      | number       | unix    | unix     | numb | numb   | unix

Lunch Table:

Clock ID |Employee ID|ClockIN|Clock Out|Year| WeekID | Mon |...|Sun|HoursID

auto      | number   | unix  | unix    |numb| numb   | unix|........| Numb

Clock Table: (used for break times)

Clock ID |Employee ID|ClockIN|Clock Out|Year| WeekID | Mon |...|Sun|HoursID

auto      | number   | unix  | unix    |numb| numb   | unix|........| Numb

我尝试了许多不同的变体,但我迷路了。这是我最后一次尝试,只是为了使其在星期一工作。

$sql= 
"SELECT 

Employee.FirstName,
Employee.LastName,
Employee.EmployeeID,


            Hours.EmployeeID,
            Hours.Year,
            Hours.WeekID,
            Hours.ClockID,

            sum(Hours.Mon) as mon,


            Clock.HoursID
            sum(Clock.Mon) as MonBreak

            Lunch.HoursID
            sum(Lunch.Mon) as MonLunch



FROM
Employee, Hours, Clock


WHERE 
 Employee.EmployeeID = Hours.EmployeeID
 AND Hours.Year = '$dt_year' AND Hours.WeekID = '$dt_week'  
AND Clock.HoursID = Hours.ClockID

GROUP BY Employee.EmployeeID
ORDER BY Employee.FirstName
";

基本上,我希望最终创建该表。

Employee Name | Mon Hours | Mon Lunch | Mon break | Tues........Sun Break|

Employee 1    | sum hours | sum lunch | sum break |...............

Employee 2    | sum hours | sum lunch | sum break |...............

Employee 3    | sum hours | sum lunch | sum break |...............

1 个答案:

答案 0 :(得分:0)

这是如何获取除工作日以外的数据:

select t2.EmployeeID, EmployeeName, MonHours, lunchtotal + sum(Clock.ClockOut - Clock.ClockIn) as MonBreak
from
(
select t.EmployeeID, EmployeeName, MonHours, sum(Lunch.ClockOut - Lunch.ClockIn) as lunchtotal
from
(
select Employee.EmployeeID concat(FirstName, ' ', LastName) as EmployeeName, sum(Hours.ClockOut - Houts.ClockIn) as MonHours
from Employee
join Hours on Employee.EmployeeID = Hours.EmployeeID
group by Employee.EmployeeID
) t
join Lunch on t.EmployeeID = Lunch.EmployeeID
group by t.EmployeeID
) t2
join Clock on t2.EmployeeID = Clock.EmployeeID
group by t2.EmployeeID

您还可以使用DAYOFWEEKcase syntax进一步找出区别工作日的方式。您将需要使用它们并将它们与总和明智地组合。