我有下表:
ID | ID_MESIN |PIC | Due Date |
________________________________________
1 | 1081 | Hariyanto |12/12/2013
2 | 1081 | Budi |13/12/2013
3 | 1059 | Jono |23/12/2013
4 | 1059 | Yuki |24/12/2013
我需要一个查询,该查询给出每个ID_MESIN列的最后一行。
例如:如果我使用ID_Mesin = 1059运行查询,则结果为
4 | 1059 | Yuki |24/12/2013`
如果我使用ID_Mesin = 1081运行查询,则结果为
2 | 1081 | Budi |13/12/2013
我有这样的查询:
SELECT * , MAX( ID ) AS ID FROM mytable WHERE ID_MESIN = '1081'
像这样:
SELECT * FROM mytable WHERE ID_MESIN = '1081' AND ID = (SELECT MAX(ID) FROM mytable)
但是结果是错误的:
2 | 1081 | Hariyanto |12/12/2013
ID和ID_MESIN为true,但其他列错误。
最佳答案
您接近:
SELECT * FROM mytable WHERE ID_MESIN = '1081'
AND ID = (SELECT MAX(ID) FROM mytable where ID_MESIN = '1081')
如果您想要所有ID_MESIN值的最高ID行:
select t.*
from mytable t
join (select id_mesin, max(id) as id from mytable group by id_mesin) m
on t.id_mesin = m.id_mesin and t.id = m.id