How to Retrieve Last Record in mysql?
I have a table name Data
with fields
Surmane
, Name
, Timestamp
, PaidMoney
, ChangAmmount
, Address
, Store
I want to have as result of a query the last record (DESC Timestamp
Limit 1) of each person (group by Surname
, Name
) with the PaidMoney
,ChangeAmmount
, Address
, Store
For example the result must be
Jones, Jim, 1290596796, 220.00, 0.25, 5th Avenue 120, Some Store1
Kojak, Ian, 1290596890, 1000.00, 50.25, Derek Avenue 1020, Some Store2
For each combination of Surname, Name must present the last record.
开发者_高级运维I try to do this with:
select `Surname`,
`Name`,
max(date_format(from_unixtime(`Timestamp`),'%Y/%m/%d - %T')) AS `dateTime`,
`PaidMoney`,
`ChangAmmount`,
`Address`,
`Store`
from `Data`
group by `Surname`, `Name`;
No good cause this doesn't show correct data.....
Please Help...
Thank you...
select t1.surname,
t1.name,
from_unixtime(t1.timestamp,'%Y/%m/%d - %T') as datetime,
t1.PaidMoney,
t1.ChangAmmount,
t1.Address,
t1.Store
from table as t1
inner join (select concat_ws(' ',name,surname) as n,max(timestamp) as timestamp
from table
group by name,surname) as t2
on t1.timestamp = t2.timestamp and concat_ws(' ',t1.name,surname) = t2.n
Your table contains redundant datas of names and surnames. It would be better if you put these datas in another table and refer to them using people id. Moreover without an id, the use of concat will slow down the join performance, even if you would have an index.
edit.
create view my_view as
select * from table t1
where timestamp = (select max(timestamp) from table as t2
where concat_ws(' ',t1.name,t1.surname) = concat_ws(' ',t2.name,t2.surname))
You should add order by timestamp DESC
to your query and change the max(...)
part to timestamp
.
You could do a subquery (ie. a nested SELECT) to get the max(date stuff) for each person, but that wouldn't be very efficient, according this page, which suggests another way that might be helpful:
http://dev.mysql.com/doc/refman/4.1/en/example-maximum-column-group-row.html
精彩评论