Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find records using having clause

Tags:

sql

database

I would like to retrieve all records having the most recent modification time. For example, taking this table:

|page_url|last_modified|
---------
|abc.com |2010-10-01 10:00:00|
|xyz.com |2010-10-04 12:10:00|
|xyz.com |2010-10-04 12:00:00|
|xyz.com |2010-10-04 10:00:00|
|abc.com |2010-10-01 08:00:00|

And output should contain following data:

|page_url|last_modified|
---------
|abc.com |2010-10-01 10:00:00|
|xyz.com |2010-10-04 12:10:00|

I have tried using having clause like below but not working for me :(

SELECT page_url, last_modified 
FROM
my_table
HAVING MAX(last_modified);

Edit 1 : I am having 25 fields in my table to use. But, I guess I can't apply group by for all. What to do now?

like image 879
Saurabh Saxena Avatar asked Feb 18 '23 21:02

Saurabh Saxena


2 Answers

No need to use HAVING on this, only GROUP BY clause.

SELECT page_url, MAX(last_modified) 
FROM my_table
GROUP BY page_url

UPDATE 1

SELECT  a.*
FROM    my_table a
        INNER JOIN
        (
            SELECT page_url, MAX(last_modified) recentDate
            FROM my_table
            GROUP BY page_url
        ) b ON a.page_url = b.page_url AND
                a.last_modified = b.recentDate
like image 144
John Woo Avatar answered Feb 25 '23 12:02

John Woo


Try to use group by and max() in select statement

SELECT page_url, max(last_modified) 
FROM  my_table
group by page_url

More information:

  • GROUP BY
  • MAX
  • HAVING
like image 33
Robert Avatar answered Feb 25 '23 12:02

Robert