2016-12-04 9 views
0

私は3つのテーブルposts,tags、およびposts_tagsを持っています。多対多のクエリ

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

これは私の記事のすべてを返しても、1:私は1

私のクエリのIDとタグを持つすべての記事を検索しようとしている

posts: 
- id 
- title 

tags: 
- id 
- text 

posts_tags: 
- id 
- post_id 
- tag_id 

タグIDが1の投稿だけでなく、さまざまなタグIDで表示されます。

答えて

2

あなたはすべてのタグに限定されており、限られたサブセットではありません。特定の試合で「どこで」句にtag_id = 1を入れて、参加する:あなたがposts_tagsでポストIDが列をpost_idの持っていることを確認し

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

ていますか? – cwallenpoole

+0

申し訳ありません私はあなたがそれに答える前にコメントを削除しました。私は私の最後に間違いを犯したこのクエリは、私があなたに感謝しているものです – Rodrigo