D555
D555

Reputation: 1840

MySql Query - Finding out the Intersect

I have 3 tables, user_tag, article_tag, article_ignored. I want to fetch only those articles of user_id = 48 for which at least one article tags matches with user tag. I am stuck in this since long time and don't have any idea how to achieve this.

The table structure is as follows:

article_ignored table
id | user_id 
1  | 48
2  | 48
3  | 48

article_tag table
id | article_id | tag_id 
1  |    1   |   1  
2  |    1   |   5
3  |    1   |   7
4  |    2   |   2
5  |    2   |   8
6  |    3   |   3
7  |    3   |   2

user_tag table
id | user_id | tag_id
1  |   48    |   2
2  |   48    |   3

Required output:

article_ignored
id
2
3

Upvotes: 0

Views: 23

Answers (1)

Giorgos Betsos
Giorgos Betsos

Reputation: 72175

You can use NOT EXISTS:

SELECT id, user_id
FROM article_ignored AS ai
WHERE EXISTS (SELECT 1
              FROM article_tag AS at
              JOIN user_tag AS ut ON at.tag_id = ut.tag_id
              WHERE ai.id = at.article_id)

Demo here

Upvotes: 1

Related Questions