简体   繁体   中英

how to get the latest record from MySQL Server database for a particular condition?

I have a database table with the fields as described in the simplified example below.

What does the sql query look like for getting the latest record for a particular type value (say type value = 4, see example)?

id - type -   details   - created
 1     4     'detailsA'   2010-09-07
 2     4     'detailsB'   2010-09-10   //this is the record to be retrieved
 3     3     'detailsC'   2010-09-14   

The only way I see is by means of 2 queries; the first query retrieving the related date (2010-09-10) by means of MAX(date), and use that value in the second query...

select id, type, details, created
from MyTable
where type = 4
order by created desc
limit 1

Try this :-

select id, type, details, created
from MyTable
where type = 4
order by created desc
limit 0,1;

Or

If on same date more than one record has entered then, you can use below query.

 select id, type, details, created
    from MyTable
    where type = 4
    order by id desc
    limit 0,1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM