build query to select data based on another table <p>tables <img src="https://i.stack.imgur.com/PbdgS.jpg" alt="enter image description here"></p> <p>sample data</p> <p>walls</p> <pre><code>wall_id wall_name 1 wall_1 2 wall_2 6 wall_6 </code></pre> <p>wall_categories</p> <pre><code>wall_id category_id 1 2 2 1 6 1 6 2 </code></pre> <p>categories</p> <pre><code>category_id category_name 1 Wallpaper 2 Photography </code></pre> <p>html</p> <pre><code>&lt;a href="file.php?category=wallpaper"&gt;Wallpaper&lt;/a&gt; &lt;a href="file.php?category=photography"&gt;Photography&lt;/a&gt; </code></pre> <p>What I need to do is when the user click the <code>Wallpaper</code> link, I want the images with <code>wallpaper</code> as category to be displayed same with <code>photography</code>. I have built an initial query but it generates duplicate records as I'm using join, there must be something else that need to be added to make it work.</p> <pre><code> SELECT DISTINCT walls.wall_id, walls.wall_name, walls.wall_views, walls.upload_date, categories.category_name FROM categories INNER JOIN wall_categories ON wall_categories.category_id=categories.category_id INNER JOIN walls ON walls.wall_id=wall_categories.wall_id; </code></pre> <p>or since the <code>category_id</code> is fixed, we can use <code>walls</code> and <code>wall_categories</code> table only. Then lets' say we can use the following html.</p> <pre><code>&lt;a href="file.php?category=1"&gt;Wallpaper&lt;/a&gt; &lt;a href="file.php?category=2"&gt;Photography&lt;/a&gt; </code></pre>