Reputation: 341
I have 3 tables:
- pages(id, name, desc)
- page_tags(id, page_id, tag_id)
- tag_posts(tag_id, post_id)
Given a page in the pages table, I want to get the posts in tag_posts table where tag_id matches ALL the tag_ids for the given page in the page_tags table.
For instance, if the entries in the 3 tables are:
1) pages:
- [1, 'page 1', 'some desc']
2) page_tags:
- [1, 1, 1],
- [2, 1, 2]
3) tag_posts:
- [1, 101],
- [2, 102],
- [1, 201],
- [3, 202]
I did a simple inner join of the 3 tables using this query:
SELECT tp.*
FROM pages p
JOIN page_tags pt ON pt.page_id = p.id
JOIN tag_posts tp ON tp.tag_id = pt.tag_id
WHERE 1
However, this returns rows 1, 2 and 3 from the sample tag_posts table above whereas I wanted only rows 1 and 2 as these two rows match ALL the tag_id rows from the first join between pages and page_tags table.
Please let me know how I can achieve this. Note: I'm using mysql.
Upvotes: 0
Views: 57
Reputation: 664
I'm confused. tag_post table does have 3 matches (row 1 2 and 3) because tag_post where tag_id = 1 is matched twice. So i would say its correct in what you are seeing.
If you are trying to find the tag_posts for a specified page then the query will be this...
SELECT tp.*
FROM pages p
JOIN page_tags pt ON pt.page_id = p.id
JOIN tag_posts tp ON tp.tag_id = pt.tag_id
WHERE p.id = 1
Upvotes: 1