0

This is my table. I want to get the url id stored on recently posted dates using mysql query. I have tried the below query

SELECT * FROM T1 GROUP BY url_id having MAX(url_post_date)
Table Name: T1

id url_id url_post_date
-----------------------
1  111    2014-03-14 18:19:59 
2  111    2014-03-14 18:20:00
3  112    2014-03-14 19:20:00
4  111    2014-03-14 18:21:00
5  113    2014-03-14 19:21:00

I want the output like:

id url_id url_post_date
-----------------------
5  113    2014-03-14 19:21:00
4  111    2014-03-14 18:21:00
3  112    2014-03-14 19:20:00

Can any one help me would be greatly appreciated.

Thanks.

aksu
  • 5,221
  • 5
  • 24
  • 39
ahalya
  • 184
  • 1
  • 10

1 Answers1

1

The teach a man to fish method:

The Rows Holding the Group-wise Maximum of a Certain Column

Task: For each article, find the dealer or dealers with the most expensive price.

This problem can be solved with a subquery like this one:

SELECT article, dealer, price
FROM   shop s1
WHERE  price=(SELECT MAX(s2.price)
              FROM shop s2
              WHERE s1.article = s2.article);

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0001 | B      |  3.99 |
|    0002 | A      | 10.99 |
|    0003 | C      |  1.69 |
|    0004 | D      | 19.95 |
+---------+--------+-------+

The preceding example uses a correlated subquery, which can be inefficient (see Section 13.2.10.7, “Correlated Subqueries”). Other possibilities for solving the problem are to use an uncorrelated subquery in the FROM clause or a LEFT JOIN.

Uncorrelated subquery:

SELECT s1.article, dealer, s1.price
FROM shop s1
JOIN (
  SELECT article, MAX(price) AS price
  FROM shop
  GROUP BY article) AS s2
  ON s1.article = s2.article AND s1.price = s2.price;

LEFT JOIN:

SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.price
WHERE s2.article IS NULL;

The LEFT JOIN works on the basis that when s1.price is at its maximum value, there is no s2.price with a greater value and the s2 rows values will be NULL.

Community
  • 1
  • 1
fancyPants
  • 50,732
  • 33
  • 89
  • 96