简体   繁体   中英

SQL Query - Join on ALL rows of a previous join

I have 3 tables:

  1. pages(id, name, desc)
  2. page_tags(id, page_id, tag_id)
  3. 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. [1, 'page 1', 'some desc']

2) page_tags:

  1. [1, 1, 1],
  2. [2, 1, 2]

3) tag_posts:

  1. [1, 101],
  2. [2, 102],
  3. [1, 201],
  4. [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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM