2014-03-30 113 views
2

我有3個表:的MySQL查詢多個表與級聯

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  | 
+----+-----------------------------+-------------+--------------------------+ 

我怎樣才能實現這個?是否可以在單個查詢中執行此操作?

SQLFiddle

感謝您的任何幫助。

+0

只是刪除'WHERE categories.name =「mysql'' –

回答

2

使用post聚合檢查,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 
; 

http://sqlfiddle.com/#!2/b1780/17

+0

謝謝,米哈伊。對於單個查詢+1。 – bprayudha