我正在尝试加入两个表格。第一个表包含员工信息,如员工编号名称等。第二个表包含时钟信息,如员工编号,状态(时钟输入或输出),上次更新日期时间,时间输入,时间输出,小时数天。
我有这样的东西,但数据库中的真实信息
employees_tbl(
employee_id INT NOT NULL AUTO_INCREMENT,
employee_first VARCHAR(30) NOT NULL,
employee_last VARCHAR(30) NOT NULL,
PRIMARY KEY ( employee_id )
);
insert into employee (employee_id, employee_first, employee_last) values (1, First, Name);
insert into employee (employee_id, employee_first, employee_last) values (2, Second, Name);
insert into employee (employee_id, employee_first, employee_last) values (3, Third, Name);
insert into employee (employee_id, employee_first, employee_last) values (4, Fourth, Name);
insert into employee (employee_id, employee_first, employee_last) values (5, Fifth, Name);
employee number, status(clocked in or out), datetime row was last updated, time clocked in, time clocked out, hours
transactions_tbl(
employee_id INT NOT NULL
status VARCHAR(3) NOT NULL,
datetime DATETIME NOT NULL,
clockin TIME,
clockout TIME,
hours TIME,
PRIMARY KEY ( employee_id )
);
INSERT INTO transactions (employee_id, status, datetime, clockin, clockout, hours) VALUES (1, "OUT", "2015-08-10 05:00:00", "2015-08-10 04:00:00", "2015-08-10 05:00:00", "01:00:00");
INSERT INTO transactions (employee_id, status, datetime, clockin, clockout, hours) VALUES (2, "IN", "2015-08-11 05:00:00", "2015-08-11 04:00:00", , );
INSERT INTO transactions (employee_id, status, datetime, clockin, clockout, hours) VALUES (3, "IN", "2015-08-11 05:00:00", "2015-08-10 04:00:00", "2015-08-10 05:00:00", "01:00:00");
我正在寻找的输出是每个员工都应该拥有他们的名字,如果他们当天有进入或进出的信息,那么应该显示信息。如果他们没有进入或离开当天,它应该只显示他们最后一次进出时间。它应该始终显示员工的最后记录,这意味着最近的活动。如果他们从未进入或退出,它仍应显示其名称。
我使用的查询是:
'SELECT employee_id, employee_first FROM employees e left join (SELECT * FROM transactions ORDER BY datetime DESC) as t1 on e.employee_id = t1.employee_id GROUP BY t1.employee_id'
然而,它只给了我前3名员工,而没有给员工4及以后。
我在mysql和php中编码。我会在这里将结果显示为表格,但无法弄清楚如何正确地制作表格格式。一切都只是陷入了混乱,我甚至无法解决问题。但希望你明白这一点。
答案 0 :(得分:3)
这是您的查询:
SELECT e.employee_id, e.employee_first
FROM employees e left join
(SELECT * FROM transactions ORDER BY datetime DESC) as t1
on e.employee_id = t1.employee_id
GROUP BY t1.employee_id;
它有几个主要错误。第一个是在t1.employee_id
中使用GROUP BY
。这是来自第二个表,而不是第一个,所以它可能是NULL
。其次,子查询中有ORDER BY
,显然希望能做某事。我还假设您确实需要来自t1
的列。
根据您描述的内容,我认为您想要:
SELECT e.employee_id, e.employee_first, t.*
FROM employees e left join
(SELECT employee_id, MAX(datetime) as maxdt
FROM transactions
GROUP BY employee_id
) tmax
on e.employee_id = tmax.employee_id left join
transactions t
on tmax.employee_id = t.employee_id and tmax.maxdt = t.datetime;
答案 1 :(得分:0)
您正在从Transactions表开始执行左连接。它只有3名员工。您的代码工作正常。如果您想要获得所有员工,请在事务表上进行正确的联接。
答案 2 :(得分:0)
为什么不
SELECT employee_id, employee_first
FROM employees e
LEFT JOIN transactions t1 on e.employee_id = t1.employee_id
GROUP BY t1.employee_id
哦,顺便说一句,你之所以得到3个结果而不是5个结果,是因为你在事务表的GROUP BY
employee_id
上做了t1
。如果您将其删除或将其更改为e.employee_id
,则应返回所需的值。