tbl_contacts: -
user_id - int
contact_id - int
first_name - varchar
last_name - varchar
date_backup - TIMESTAMP
I am having lots of data and i want to get the latest one from the database.
Currently I am having data of 2 different dates, 1 is 2014-02-12 04:47:39 and another is 2014-01-12 04:47:39. I am having total 125 records from which 5 are of 2014-01-12 04:47:39 date and rest are of 2014-02-12 04:47:39. I am using below query to get the latest date data but its returning all the data somehow. I am trying since long and unable to successfully achieve my goal. If anyone has any idea please kindly help me.
Query
SELECT `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name`
FROM tbl_contacts WHERE `date_backup` IN (
SELECT MAX(`date_backup`)
FROM tbl_contacts WHERE `user_id`= 1 GROUP BY `contact_id`
)
ORDER BY `contact_id`ASC, `date_backup` DESC
By using ORDER BY date_backup
DESC, I am getting the old data at the end of list. But i just don't want the old date record at all if new date record is available.
user MySql
UNIX_TIMESTAMP()
with ORDER BY
Clause.
SELECT `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name`
FROM tbl_contacts WHERE `date_backup` IN (
SELECT MAX(`date_backup`)
FROM tbl_contacts WHERE `user_id`= 1 GROUP BY `contact_id`
)
ORDER BY UNIX_TIMESTAMP(`date_backup`) DESC, `contact_id`ASC
If require change all date_backup
with UNIX_TIMESTAMP(`date_backup`)
LIMIT will do the trick in MySQL database (in other databases it would probably be TOP clause). So use LIMIT 10 :
SELECT TOP 1 `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name`
FROM tbl_contacts WHERE `date_backup` IN (
SELECT MAX(`date_backup`)
FROM tbl_contacts WHERE `user_id`= 1 GROUP BY `contact_id`
)
ORDER BY `contact_id`ASC, `date_backup` DESC
LIMIT 10
If you want ten of the most recent ones.
The guide for the LIMIT clause can be found at MySQL reference
只需在查询末尾添加LIMIT 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.