reloj mysql

I have a timeclock table with the following elements (id(pk), action, emp_id(fk), time).

How can I select the latest action if I pass the emp_id a la consulta?

id  emp_id  action  current_time
-----------------------------------------------
1   1   clockin     2012-01-29 21:52:38
2   1   clockout    2012-01-29 21:54:24
3   3   clock in    2012-01-30 21:10:51
4   4   clock in    2012-01-30 21:10:51
5   9   clock in    2012-01-30 21:11:05
6   10  clock in    2012-01-30 21:11:05
7   10  go to meal  2012-01-30 21:11:38
8   9   go to meal  2012-01-30 21:11:38
9   9   back        2012-01-30 21:12:53
10  3   back        2012-01-30 21:12:53
11  2   back        2012-01-30 21:12:53
12  1   back        2012-01-30 21:12:53

If I write my query like this:

SELECT MAX(ID) FROM timeclock WHERE emp_id = 1 

I get 12 which is right but if i

SELECT MAX(ID) , action FROM timeclock WHERE emp_id = 1

yo obtengo id->12 y action -> 'clockin' en lugar de 'back' which is definitely not right

preguntado el 01 de febrero de 12 a las 03:02

1 Respuestas

Te estás perdiendo un GROUP BY cláusula para tu MAX() aggregate. The reason you got the correct answer 12 for your first query attempt was merely because that happens to be the greatest ID in the table while also coincidentally belonging to emp_id = 1. You would have gotten the same result for any of the emp_id valores. A GROUP BY clause will sort this out.

Here is an example retrieving the whole row for the associated record:

SELECT * FROM timeclock 
WHERE id = (SELECT MAX(id) AS id FROM timeclock WHERE emp_id = 1 GROUP BY emp_id);

Esto también se puede hacer con un HAVING clause, not needing the subquery:

SELECT action 
FROM timeclock 
WHERE emp_id = 1
GROUP BY emp_id
HAVING id = MAX(id);

Para referencia, the MySQL aggregate functions reference.

Respondido 01 Feb 12, 07:02

works fine thanks michael i checked this out at w3schools.com it makes it easy for me to understand - user1170618

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.