2014-04-21 60 views
0

我有一個包含博客文章的網站。帖子可以有一個或多個類別。 現在我想要一個查詢,返回所有類別的列表,這些列表由博客文章日期排序。 我已經在SELECT查詢中嘗試了SELECT,但這不起作用... 我該如何做,並返回按日期排序的類別?按商品日期排序的退貨類別

表博客:

|id------|title------------------|date------| 
|1  |Test title    |2014-05-05| 
|2  |Test title 2   |2014-04-01| 
|3  |Last test title  |2014-02-02| 
|4  |Another blog item  |2014-01-06| 

表類:

|id|category-----| 
|1 |computers | 
|2 |home   | 
|3 |work   | 

表blogs_categories:

|blog_id|category_id| 
|1  |1   | 
|2  |1   | 
|4  |2   | 

回答

0

用一個簡單的加入,只選擇類別不同的​​數據

SELECT DISTINCT c.* 
FROM categories c 
LEFT JOIN blogs_categories bc ON(c.id =bc.category_id) 
LEFT JOIN blogs b ON(b.id=bc.blog_id) 
ORDER BY b.date DESC 

Fiddle Demo

0
SELECT c.*, 
     b.`date` 
FROM categories as c 
LEFT JOIN blogs_categories as bc on bc.category_id=c.id 
LEFT JOIN (
    SELECT `id`, max(`date`) as `date` 
    FROM blogs 
    GROUP BY `id` 
) as b on b.`id`=bc.`blog_id` 
GROUP BY c.`id` 
ORDER BY b.`date` desc