简体   繁体   中英

Query to select last record which has same column value(date)

table schema

id              date
----            -------
1020            1990-02-15
1020            1990-02-15
1060            1990-02-15
1020            1990-03-15
1020            1990-03-15
1020            1990-02-10

query to select last inserted record which has same date and where id = 1020 date format yyyy-mm-dd

根据最后一条记录,我假设您的意思是日期最新的那个....

select * from table where id=1020 order by date desc limit 1

Since it's MySQL

 
 
 
 
  
  
  SELECT * FROM table WHERE id=1020 ORDER BY `date` desc LIMIT 1
 
 
 

but i still have a question for you, what if you have records like this?

 
 
 
 
  
  
  1020 1/11/12 1020 1/12/12 1020 1/12/12 1020 1/13/12
 
 
 

what will it return?

In your case, the date is not currently formatted ( i guess it was saved as VARCHAR ) that is why you need to format it back to date using STR_TO_DATE function and from that display using your desired format.

 
 
 
 
  
  
  SELECT DATE_FORMAT(STR_TO_DATE(`date`, '%m/%d/%y'), '%d-%m-%Y') lastDate FROM table WHERE id = 1020 ORDER BY `date` desc LIMIT 1
 
 
 

UPDATE 1

So you need the record which has the same date right? Try this edit one. For this, it created a subquery which returns the latest date and has the same date.

 SELECT * FROM tablename WHERE id = 1020 AND `Date` = ( SELECT MAX(`date`) maxDate FROM tableName GROUP BY `date` HAVING COUNT(`DATE`) > 1 )

这有帮助吗?

select max(date) from table where id=1020;

Try with

SELECT * FROM schema WHERE id=1020 ORDERBY date DESC limit 1;

or choose max of the date you have like

SELECT MAX(date) from schema WHERE id = 1020;

使用 max() 并将您的主列分组

select id, max(date) from tableName group by id;

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