2016-12-04 102 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