我有一个 articles
table 和一个 categories
像这样的表格:
articles
-----------------------------------------------
| id | datetime | title | categoryid | status |
-----------------------------------------------
categories
-------------
| id | name |
-------------
我需要从每个类别中获取最新的文章日期,例如:
result
----------------------------------------------------------
| category id | category name | most recent article date |
----------------------------------------------------------
结果必须包含所有类别 + 每个类别的最新文章(状态 = 0)日期。
它的结果必须与 select * from categories
完全一样加上显示 datetime
的新行BUT ONLY IF THE ARTICLE STATUS IS 0 类别的最新文章。
清楚了吗?
我需要它的原因是因为我正在尝试制作动态站点地图并且我需要每个类别的最新文章的时间显示在 <lastmod>
上类别列表的标记。
$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 适应状态
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
输出
| ID | NAME | RECENT_DT |
-------------------------------
| 1 | Category1 | 2013-03-19 |
| 2 | Category2 | 2013-03-17 |
| 3 | Category3 | (null) |
这是 SQLFiddle
边注
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.
关于php - 如何获取每个类别的最新文章日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537978/