Selecting an item matching multiple tags

后端 未结 2 1504
野性不改
野性不改 2021-01-05 15:38

This seems very basic but I can\'t figure it out.

I\'ve got a table \"item_tags\", and I want to select all of the items that match tags 1 and 2 (as in, each item ha

相关标签:
2条回答
  • 2021-01-05 16:08

    Use:

      SELECT i.uid
        FROM ITEMS i
        JOIN ITEM_TAGS it ON it.uid_local = i.uid
                       AND it.uid_foreign IN (1, 2)
    GROUP BY i.uid
      HAVING COUNT(DISTINCT it.uid_foreign) = 2
    

    You need to have a GROUP BY and HAVING clause defined, and the count of distinct tag ids must equal the number of tags you specify in the IN clause.

    0 讨论(0)
  • 2021-01-05 16:19

    something like this?

    SELECT i.* from items i inner join items_tags it
    on i.id = it.item_id
    inner join tags t
    on t.id = it.tag_id
    WHERE t.name in ('tag1', 'tag2');
    

    EDIT:

    suppouse you have items_tags: (item_id, tag_id) as table

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