I am using MySQLi to pull blog post information from a database onto my website. My database currently has 3 tables with the following relevant columns:
- blog_posts: id,
- blog_post_tags: blog_post_id, tag_id,
- tags: id, name
I am trying to select all blog posts by tag name and this is the query that I am using:
SELECT blog_posts.*
FROM blog_post_tags
LEFT JOIN (blog_posts)
ON (blog_post_tags.blog_post_id = blog_posts.id)
WHERE blog_post_tags.tag_id
IN (
SELECT id FROM tags
WHERE name=$in_tag_name
)
where $in_tag_name is my PHP variable representing the name of the selected tag. However, I am not very experienced with SQL so I'm not sure if there is a more performant approach here than using a nested select.
To remove the nested select, I've considered instead of having 3 tables, just having 2 tables with the following relevant columns:
- blog_posts: id,
- blog_post_tags: blog_post_id, tag_name,
Then I considered the query:
SELECT blog_posts.*
FROM blog_post_tags
LEFT JOIN (blog_posts)
ON (blog_post_tags.blog_post_id = blog_posts.id)
WHERE blog_post_tags.tag_name=$in_tag_name
This approach gets rid of the nested query but feels less intuitive by not separating the tags table information fully from the blog posts table information.
I'm wondering if there is a best approach here of the two database structures, or else a better query than the nested select in the first database structure. I'm not sure if this is a silly question or if I'm overcomplicating things so if anyone can nudge me in the right direction here, that would be much appreciated!