【问题标题】:How to Retrieve Last Record in mysql?如何在mysql中检索最后一条记录?
【发布时间】:2012-06-16 03:35:50
【问题描述】:

我有一个表名Data 和字段
SurmaneNameTimestampPaidMoneyChangAmmountAddressStore

我希望通过PaidMoney,ChangeAmmount,Address 查询每个人(按SurnameName 分组)的最后一条记录(DESC Timestamp 限制1) , 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 的每个组合,Name 必须显示最后一条记录。

我尝试这样做:

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`;

不好,因为这不显示正确的数据.....

请帮忙...

谢谢...

【问题讨论】:

    标签: mysql


    【解决方案1】:
    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
    

    您的表格包含冗余的姓名和姓氏数据。 如果将这些数据放在另一个表中并使用人员 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))     
    

    【讨论】:

    • 非常感谢......!!!我现在的第二个问题是我无法创建此视图....我收到消息“视图的 SELECT 包含 FROM 子句中的子查询”....
    【解决方案2】:

    您应该将order by timestamp DESC 添加到您的查询中,并将max(...) 部分更改为timestamp

    【讨论】:

    • 这如何确保包含正确的商店和付款?
    【解决方案3】:

    您可以执行子查询(即嵌套的 SELECT)来获取每个人的最大(日期内容),但这不会非常有效,根据此页面,这提出了另一种可能有用的方法:

    http://dev.mysql.com/doc/refman/4.1/en/example-maximum-column-group-row.html

    【讨论】:

      猜你喜欢
      • 2010-11-21
      相关资源
      最近更新 更多