mysqlruby-on-railsrubyactiverecordsearchlogic

How do you do this in mysql or rails


Say you have a posts table and a tags table, and both are related by a post_tags table.

so

posts has id/subject/body columns

tags has id/name

post_tags has id/post_id/tag_id

in rails terminology, I have a Post Model that has many Tags through AssetTags.

I'm trying to query for a post that has 2 specific tags. so if there is a rails tag and a mysql tag, I want a query that returns a post that only has those two tags.

make sense?

Any way to do this with activerecord (I'm using search logic) or mysql?


Solution

  • This SQL returns the posts that contain both tags.

    select 
      p.* 
    from 
      posts p
      ,asset_tags atg1
      ,asset_tags atg2
      ,tags t1
      ,tags t2
    where
      p.id = atg1.post_id
    and t1.id = atg1.tag_id
    and t1.tag = 'MySQL' 
    and p.id = atg2.post_id
    and t2.id = atg2.tag_id
    and t2.tag = 'Rails'
    ;
    

    As for doing it via Active record, an alternative would be to query for each of the tags and then & the resulting arrays to get the intersection of the two.