Mysql join query for multiple “tags” (many-to-many relationship) that matches ALL tags?

前端 未结 1 1609
攒了一身酷
攒了一身酷 2020-12-02 08:41

I am trying to query for Objects that match ALL of a given set of Tags.

Basically I want users to be able to add on more and more Tags to filter or \"narrow down\"

相关标签:
1条回答
  • 2020-12-02 09:18

    Use:

      SELECT * 
        FROM OBJECTS o
        JOIN OBJECTSTAGS ot ON ot.object_id = o.id
        JOIN TAGS t ON t.id = ot.tag_id
       WHERE t.name IN ('tag1','tag2')
    GROUP BY o.id
      HAVING COUNT(DISTINCT t.name) = 2
    

    You were missing the HAVING clause.

    There's no need to LEFT JOIN if you want only rows where both tags exist.

    0 讨论(0)
提交回复
热议问题