2013-03-21 74 views
0

我有一個articles表和categories表是這樣的:如何獲得每個類別中最最近的一篇文章日期

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

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

我需要獲得最新的文章從每個類別日期的選擇,像:

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

結果必須包含每個類別的所有類別+最近的文章(狀態= 0)日期。

它必須產生酷似select * from categories PLUS顯示類別的最最近搜索文章的datetime但只有當文章狀態爲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> 
<?} 
+1

你試過了什麼SQL語句?可能重複:http://stackoverflow.com/questions/3869426/mysql-join-most-recent-matching-record-from-one-table-to-another – Jon 2013-03-21 01:40:31

回答

3

UPDATE2,以適應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 

輸出

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

這裏是SQLFiddle

而且在一個側面說明

請不要將mysql_ *函數用於新代碼。他們是 deprecated。使用prepared statementsPDOMySQLi。這是一個很好的PDO tutorial

+0

太棒了!有用。還有一件事。我有一些沒有文章的類別,但我想列舉它們。那可能嗎?我不想打擾你。如果你不回答我,我會理解。謝謝。 – 2013-03-21 01:50:15

+0

當然這是可能的,並且像將「LEFT」連接更改爲「RIGHT」一樣簡單,或者我們可以用「LEFT」連接交換表重寫它。查看更新的答案和sqlfiddle。 – peterm 2013-03-21 01:55:58

+0

它的完美現在,peterm!非常感謝你的幫助。 – 2013-03-21 02:00:14

相關問題