Reputation: 35
I have 2 tables in PHP MyAdmin, first is tb_data_log
that stores all information from data records. I need to find time-in
and time-out
from first table and then extract the value to second table that is tb_attendance
. Look at image bellow:
tb_data_log
uid date time
1 28/01/2017 07.12
1 28/01/2017 16.02
2 28/01/2017 07.05
2 28/01/2017 16.23
3 28/01/2017 07.00
3 28/01/2017 16.16
1 29/01/2017 07.24
1 29/01/2017 16.11
2 29/01/2017 07.09
2 29/01/2017 16.45
3 29/01/2017 07.12
3 29/01/2017 16.02
1 30/01/2017 07.12
1 30/01/2017 16.02
2 30/01/2017 07.29
2 30/01/2017 16.19
3 30/01/2017 07.22
3 30/01/2017 16.56
I need my table to look like this bellow:
tb_attendance
uid date time_in time_out
1 28/01/2017 07.12 16.02
2 28/01/2017 07.05 16.23
3 28/01/2017 07.00 16.16
1 29/01/2017 07.24 16.11
2 29/01/2017 07.09 16.45
3 29/01/2017 07.12 16.02
1 30/01/2017 07.12 16.02
2 30/01/2017 07.29 16.19
3 30/01/2017 07.22 16.56
I think it is basically simple, but I have no idea how to write the codes in MySQL. How am I supposed to do that? Thanks!
Upvotes: 0
Views: 55
Reputation: 136
insert into tb_attendance
select a.uid,
a.date,
a.time as 'time_in',
(select b.time from tb_data_log b where a.uid = b.uid and b.time >
a.time and a.date = b.date limit 1) as 'time_out'
from tb_data_log a group by a.uid,a.date order by a.date,a.uid;
Upvotes: 0
Reputation: 866
This SQL should do the task:
INSERT INTO `tb_attendance`
SELECT `uid`,
`date`,
Min(`time`) AS 'time_in',
Max(`time`) AS 'time_out'
FROM `tb_data_log`
GROUP BY `date`,
`uid`;
Provided that you have the following field types:
`uid` INT,
`date` DATE,
`time` TIME
Upvotes: 1