Finding posts with tag1 AND tag2? (using a join-table) Exists / Having / subqueries… What to use?

前端 未结 2 846
自闭症患者
自闭症患者 2021-01-28 05:08

I need to make a query to search and filter on multiple terms.

I have a table with weapons and all can have multiple tags. I want to be able to create a filter o

2条回答
  •  北海茫月
    2021-01-28 05:36

    Turn it around. That is start with tag IN ('blue', 'old') in the innermost subquery. From that, find the tag_ids. From them, find the weapon_ids HAVING COUNT(*) = 2. Last, in the outermost query, get the weapon.name.

    No EXISTS(). No LEFT JOINs; I'm not sure you needed LEFT in the first place.

    Your original attempt needed to join to tag twice with different aliases. I avoid that by using the IN and HAVING.

    More

    Yeah, that gets a bit tricky...

    SELECT
         FROM  
          ( SELECT  weapon_id
                FROM  weapon_tags
                JOIN  weapon_tag_links USING(tag_id)
                WHERE  tag IN ('blue', 'old')
                GROUP BY  weapon_id
                HAVING  COUNT(*) >= 2 
          ) a
        JOIN  weapons w ON w.id = a.weapon_id;
    

    It would be easier if you had not normalized tags.

提交回复
热议问题