返回按文章日期排序的类别

时间:2014-04-21 15:18:23

标签: php mysql select subquery

我是一个有博客文章的网站。帖子可以包含1个或更多类别。 现在我想要一个返回所有类别列表的查询,按照博客文章日期排序。 我在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          |

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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