mysql查询获取最新记录忽略旧条目

时间:2015-09-22 04:37:54

标签: mysql

需要帮助以相同的手机号码和相同的代码获取除旧条目之外的所有最新记录:

id  |   mobile_number   |   code    |   chapter_id
1   |   123123          |   3       |   1
2   |   123124          |   4       |   1
3   |   123123          |   4       |   1
4   |   123124          |   3       |   1
5   |   123122          |   3       |   1   

输出应该是这样的

1   |   123123          |   3       |   1
3   |   123123          |   4       |   1
4   |   123124          |   3       |   1
5   |   123122          |   3       |   1   

由于

3 个答案:

答案 0 :(得分:3)

你可以试试这个查询。

SELECT `id`,`mobile_number`,`code`,`chapter_id`
FROM test_table 
WHERE id in (SELECT MAX(id) from test_table GROUP BY `mobile_number`)

这对你有用。

答案 1 :(得分:1)

尝试

SELECT * FROM table_name GROUP BY mobile_number  ORDER BY code DESC

答案 2 :(得分:0)

你可以试试这个:

select id,mobile_number,code,chapter_id from(
    select id,mobile_number,code,chapter_id,
    case when mobile_number = @ck then @rownum := @rownum+1 else @rownum:=0 end as n,
    @ck:= mobile_number as c
    from yourtable
    inner join(select @rownum :=0 ,@id := '') as x
    order by mobile_number,id desc
)as t
where n = 0