Mysql查询获取最后输入的状态值

时间:2012-10-02 17:37:02

标签: mysql

我有一张这样的桌子 -

+----+---------------------+------------+---------+--------------------+
| id | check_date          | number     | status  | sid                |
+----+---------------------+------------+---------+--------------------+
|  5 | 2012-09-29 17:44:34 | 3366064235 | SUCCESS | 1348940709163284   |
|  6 | 2012-09-29 19:40:30 | 3366064235 | FAILED  | 12345678876543     |
|  7 | 2012-09-29 17:47:30 | 4466064235 | SUCCESS | 7895345678876543   |
|  8 | 2012-09-29 19:47:30 | 4466064235 | SUCCESS | 789876545678876543 |
+----+---------------------+------------+---------+--------------------+

我想获得每个号码的最新更新状态。我怎么得到这个?我通过check_date desc尝试按编号顺序分组,但它不起作用。

2 个答案:

答案 0 :(得分:5)

您可以使用以下内容:

select t1.id, 
    t1.check_date,
    t1.number,
    t1.status
from yourtable t1
inner join
(
    select max(check_date) maxdate, number
    from yourtable
    group by number
) t2
    on t1.check_date = t2.maxdate
    and t1.number = t2.number

请参阅SQL Fiddle with demo

答案 1 :(得分:0)

select number, Status, Check_date from MYTable A
where check_date = (select max(Check_date) from MYTable where number=A.number)