简体   繁体   中英

How to get the most recent article date for each category

I have an articles table and a categories table like this:

 articles
-----------------------------------------------
| id | datetime | title | categoryid | status |
-----------------------------------------------

 categories
-------------
| id | name |
-------------

I need to get the most recent articles date from each category in a select, like:

 result
----------------------------------------------------------
| category id | category name | most recent article date | 
----------------------------------------------------------

The result must contain all categories + most recent article (with status = 0) date for each category.

Its must result exactly like select * from categories PLUS a new row showing the datetime of the most recente article of the category BUT ONLY IF THE ARTICLE STATUS IS 0 .

Is that clear?

The reason I need that is because I'm trying to make a dynamic sitemap and I need the time of the latest article to each category to show on <lastmod> tag for the categories listing.

$sql = mysql_query(".....?......");

while ($string = mysql_fetch_array($sql)){?>
    <url>
        <loc>http://www.url.com/<?echo $string['id'];?>/<?echo generate_seo_link($string['name']);?>/</loc>
        <priority>0.5</priority>
        <changefreq>daily</changefreq>
        <lastmod><? echo date("d/m/Y H:i:s", strtotime($string['date'])); ?></lastmod>
    </url>
<?} 

UPDATE2 To accomodate status

SELECT c.id, c.name, MAX(a.datetime) most_recent
  FROM articles a RIGHT JOIN
       categories c ON a.categoryid = c.id
 WHERE a.status IS NULL OR a.status = 0
 GROUP BY c.id, c.name

Output

| ID |      NAME |  RECENT_DT |
-------------------------------
|  1 | Category1 | 2013-03-19 |
|  2 | Category2 | 2013-03-17 |
|  3 | Category3 |     (null) |

Here is SQLFiddle

And on a side note

Please, don't use mysql_* functions for new code. They are deprecated . Use prepared statements with either PDO or MySQLi . Here is a good PDO tutorial .

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