MySQL:加入3个表并按其中一个过滤

时间:2013-11-14 02:40:23

标签: mysql join blogs

我有三个包含以下列的表:

blog:  
id | title | body

categories:
id | title

blog_categories_join: 
blog_id | category_id

我正在使用此MySQL查询获取前8篇博文并加入每个帖子的相应类别:

SELECT b.* 
GROUP_CONCAT(c.title ORDER BY c.id ASC SEPARATOR ', ') AS categories,
FROM blog b
LEFT OUTER JOIN blog_categories_join bcj ON bcj.blog_id = b.id
LEFT OUTER JOIN categories c ON c.id = bcj.category_id
GROUP BY b.title
ORDER BY b.date DESC LIMIT 8

这对我很有用。但是,我想获得特定类别的前8篇博客文章。所以我尝试添加一个WHERE子句:

SELECT b.* 
GROUP_CONCAT(c.title ORDER BY c.id ASC SEPARATOR ', ') AS categories,
FROM blog b
LEFT OUTER JOIN blog_categories_join bcj ON bcj.blog_id = b.id
LEFT OUTER JOIN categories c ON c.id = bcj.category_id
WHERE bcj.category_id = $id 
GROUP BY b.title
ORDER BY b.date DESC LIMIT 8

这是因为它只从指定的类别中提取博客,但我的GROUP_CONCAT不再包含博客所属的每个类别。它仅包含WHERE子句中指定的类别。

我是否可以仅查询属于指定类别的帖子,并以我的表格结构的方式返回其各自的类别?

1 个答案:

答案 0 :(得分:0)

您应该只需重新加入类别即可使用group_concat。

SELECT
    b.*
    GROUP_CONCAT(c2.title ORDER BY c2.id ASC SEPARATOR ', ') AS categories,
FROM blog b
LEFT OUTER JOIN blog_categories_join bcj ON bcj.blog_id = b.id
LEFT OUTER JOIN categories c ON c.id = bcj.category_id
LEFT OUTER JOIN categories c2 ON c2.id = bcj.category_id
WHERE c.category_id = $id
GROUP BY b.title
ORDER BY b.date
DESC LIMIT 8