sql - many-to-many query -
i have problem , dont know better solution. okay, have 2 tables: posts(id, title), posts_tags(post_id, tag_id). have next task: must select posts tags ids example 4, 10 , 11. not exactly, post have other tags @ same time. so, how more optimized? creating temporary table in each query? or may kind of stored procedure? in future, user ask script select posts count of tags (it 1 tag or 10 @ same time) , must sure method choose best method problem. sorry english, thx attention.
this solution assumes (post_id, tag_id) in post_tags enforced unique:
select id, title posts inner join post_tag on post_tag.post_id = posts.id tag_id in (4, 6, 10) group id, title having count(*) = 3
although it's not solution possible tag combinations, it's easy create dynamic sql. change other sets of tags, change in () list have tags, , count(*) = check number of tags specified. advantage of solution on cascading bunch of joins don't have add joins, or terms, when change request.
Comments
Post a Comment