1

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

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 子句中指定的类别。

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

4

1 回答 1

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
于 2013-11-14T16:26:40.673 回答