2016-12-04 99 views
0

我有3個表格posts,tagsposts_tags多對多原始查詢

posts: 
- id 
- title 

tags: 
- id 
- text 

posts_tags: 
- id 
- post_id 
- tag_id 

我試圖找回所有有標籤與1

我的查詢的ID的帖子:

SELECT * FROM posts LEFT OUTER JOIN posts_tags ON posts_tags.tag_id = 1; 

這是返回所有我的職位,甚至是一個使用不同的標籤ID,而不僅僅是標籤ID爲1的帖子。

回答

2

您綁定到所有標籤,而不是有限的子集。把tag_id = 1成「where」子句,並加入具有特定匹配:

SELECT * 
FROM posts p 
-- You don't care about non-matches, so use an inner join to automatically filter those 
INNER JOIN posts_tags pt 
    -- JOIN looks for times when this condition evaluates to true 
    -- If I just test for tag_id = 1, if it's true for one tag, it's true for all posts. 
    -- Instead, I look for places where the two tables match up. 
    ON p.id = pt.post_id 
WHERE pt.tag_id = 1 
+0

你確定你在posts_tags後的ID POST_ID列? – cwallenpoole

+0

對不起,我看到你回答之前刪除了評論。我在結束時犯了一個錯誤,這個查詢正是我要找的謝謝 – Rodrigo