如何检索mysql中的最后一条记录?
我有一个字段的表名Data
Surmane
,Name
,Timestamp
,PaidMoney
,ChangAmmount
,Address
,Store
如何检索mysql中的最后一条记录?
我想有作为查询的最后一条记录的结果(DESC Timestamp
限制1)每个人的(由Surname
基,Name
)与PaidMoney
,ChangeAmmount
,Address
,Store
例如其结果必然是
Jones, Jim, 1290596796, 220.00, 0.25, 5th Avenue 120, Some Store1
Kojak, Ian, 1290596890, 1000.00, 50.25, Derek Avenue 1020, Some Store2
对于Surname的每个组合,名称必须出现最后一条记录。
我试着这样做:
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`;
没有正当理由,这并不表明正确的数据.....
请帮助...
谢谢。 。
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
你的表包含名字和姓氏的冗余DATAS。 如果将这些数据放在另一个表中并使用人员ID引用它们会更好。 此外,如果没有id,则即使您有索引,concat的使用也会降低联接性能。
编辑。
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))
您应该将order by timestamp DESC
添加到您的查询并将max(...)
部分更改为timestamp
。
这是如何确保包含正确的商店和付款? – Martijn 2011-04-08 12:12:10
根据这个页面,你可以做一个子查询(即嵌套的SELECT)来获取每个人的最大值(日期的东西),但这不是非常有效,这表明另一种可能有用的方法:
http://dev.mysql.com/doc/refman/4.1/en/example-maximum-column-group-row.html
非常感谢你..... !!!我现在的第二个问题是我无法制作这个视图....我收到消息“视图的SELECT包含FROM子句中的一个子查询”.... – 2011-04-08 14:47:58
我已经更新了我的答案,以便您可以使用视图:) – 2011-04-08 15:18:44
谢谢先生! – 2011-04-08 15:23:45