Sanooj T Sanooj T - 2 months ago 5
MySQL Question

Tag based search relating another Table in PHP

I have three tables

Blog table

id blog description
1 Simple PHP Nothing But simple
2 Simple JS Nothing But JS


Second Table is Tags

id tag
1 JS
2 PHP
3 mysql


Third Table is Blog_Tag

id blog_id tag_id
1 1 2
2 1 3
3 2 1


So what I need is a search based
tag

here is what I tried

For example If I search with PHP and Mysql Tags Blog with id 1 should come

Select Blog.* From Blog B INNER JOIN Blog_Tag BT ON(B.id=BT.blog_id)
WHERE BT.tag_id = 2 OR BT.tag_id=3


But this query outputs Blog 1 multiple times.any solutions?

Answer

The reason behind this in both tag_id 2 and 3 Same Blog.ID comes. Look at this query

Select B.*,BT.tag_id From Blog B INNER JOIN Blog_Tag BT ON(B.id=BT.blog_id) 
 WHERE BT.tag_id = 2 OR BT.tag_id=3 

For the Solution for unique data you need to use Distinct like i use in below query

Select DISTINCT B.* From Blog B INNER JOIN Blog_Tag BT ON(B.id=BT.blog_id) WHERE BT.tag_id = 2 OR BT.tag_id=3

Comments