我有3张桌子:
mysql> SELECT * FROM blogs;
+----+-----------------------------+-------------+
| id | title | content |
+----+-----------------------------+-------------+
| 1 | article about js & jquery | lorem ipsum |
| 2 | article about php & mysql | lorem ipsum |
| 3 | article about rails & mysql | lorem ipsum |
| 4 | article about rails & js | lorem ipsum |
+----+-----------------------------+-------------+
mysql> select * FROM categories;
+----+---------------+
| id | name |
+----+---------------+
| 1 | javascript |
| 2 | jquery |
| 3 | php |
| 4 | mysql |
| 5 | ruby-on-rails |
+----+---------------+
mysql> SELECT * FROM blogs_categories;
+----+---------+-------------+
| id | blog_id | category_id |
+----+---------+-------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 2 | 4 |
| 5 | 3 | 4 |
| 6 | 3 | 5 |
| 7 | 4 | 1 |
| 8 | 4 | 5 |
+----+---------+-------------+
问题:如何按类别获取所有博客,但是为我提供与博客本身相关的所有类别?
示例:我想获取类别mysql
中的所有博客。
到目前为止,我已尝试过此查询:
SELECT
blogs.*,
GROUP_CONCAT(categories.name SEPARATOR ",") AS categories
FROM
blogs
INNER JOIN
blogs_categories
ON blogs.id = blogs_categories.blog_id
INNER JOIN
categories
ON categories.id = blogs_categories.category_id
WHERE
categories.name = 'mysql'
GROUP BY
blogs.id
但它给了我意想不到的结果:
+----+-----------------------------+-------------+------------+
| id | title | content | categories |
+----+-----------------------------+-------------+------------+
| 2 | article about php & mysql | lorem ipsum | mysql |
| 3 | article about rails & mysql | lorem ipsum | mysql |
+----+-----------------------------+-------------+------------+
我想要的结果是:
+----+-----------------------------+-------------+--------------------------+
| id | title | content | categories |
+----+-----------------------------+-------------+--------------------------+
| 2 | article about php & mysql | lorem ipsum | php,mysql |
| 3 | article about rails & mysql | lorem ipsum | mysql,ruby-on-rails |
+----+-----------------------------+-------------+--------------------------+
我怎样才能做到这一点?是否可以在单个查询中执行此操作?
感谢您的帮助。
答案 0 :(得分:2)
使用帖子后聚合检查,WHERE
引用SELECT
中的列,因此限制它们,HAVING
引用GROUP BY
中的值。
SELECT
blogs.*,
GROUP_CONCAT(categories.name ) AS categories
FROM
blogs
INNER JOIN
blogs_categories
ON blogs.id = blogs_categories.blog_id
JOIN
categories
ON categories.id = blogs_categories.category_id
GROUP BY
blogs.id
HAVING
SUM(categories.name='mysql')>0
;