Search code examples
mysqlsqlsql-match-all

SQL Query on four tables with MySQL - 'intersection'


I have 4 tables

POST:
id

POST_TAG:
post_id
tag_id
value

TAG:
id

SEARCH:
tag_id
post_tag_value

I need to query for posts who have all tags and values as rows in SEARCH table ( not just one equal value for a tag):

EDIT: Sorry for not providing current query and enough information.

SELECT POST.id FROM POST,POST_TAG, SEARCH
WHERE
      POST.id = POST_TAG.post_id AND
      POST_TAG.tag_id= SEARCH.tag_id AND
      POST_TAG.value = SEARCH.value;

It works if SEARCH table has one row. The problem is, when it has more. There should be less results, but there are actually more( if test with 2 rows, the proper results are the rows that are duplicated; I am lookng for intersection not union)

Added sqlfiddle: http://sqlfiddle.com/#!2/9cfb9/1

The result from the query is '1','1','2' . It should be only '1', because it has both 'tags' while '2' has only one.


Solution

  • working example: http://sqlfiddle.com/#!2/393eb/39

    SELECT pt.post_id
    FROM SEARCH s INNER JOIN post_tag pt ON pt.tag_id = s.tag_id AND pt.value = s.value
    GROUP BY pt.post_id
    HAVING COUNT(*) = (SELECT COUNT(*) FROM SEARCH)
    

    Please note that in your fiddle the post with id 0 should be returned as well since it has both (0,'yes') and (1, 'yes') tuples.