2013-11-27 61 views
1

昨天我問這個問題的一個元素:結合表,同時尋找

MySQL how do I combine these tables?

我想通過自己的標籤來搜索相關博客文章,我該怎麼辦呢?

同樣,我的表是:

blog_posts 
    int id (auto increment) 
    varchar(255) title 
    text content 

blog_tags 
    int id (auto increment) 
    varchar(63) name 

blog_posttags 
    int id (auto increment) 
    int post_id 
    int tag_id 

我公司目前擁有用於搜索博客帖子由它的標籤下面的查詢,但我也希望它是標籤(就像我剛纔的問題)。

SELECT a.* 
FROM blog_posts a, 
     blog_tags b, 
     blog_posttags c 
WHERE b.id = c.tag_id 
     AND c.post_id = a.id 
     AND b.name = "searchTag" 
GROUP BY a.id 

但是,這顯然不會隨着博客帖子信息返回任何標籤。

這可以在一個查詢中完成嗎?因爲這個標籤可能有多個blogpost,我不想爲每個blogpost運行查詢來查找他們的標籤。

回答

1

你可以結合你的其他查詢與這一個。試試這個:

​​

sqlfiddle demo

+0

就像一個魅力!謝謝! –