MySQL Limit with Many to Many Relationship

后端 未结 4 747
傲寒
傲寒 2021-02-06 18:43

Given a SCHEMA for implementing tags

ITEM ItemId, ItemContent

TAG TagId, TagName

ITEM_TAG ItemId, TagId

What is the best way to limit the number

4条回答
  •  甜味超标
    2021-02-06 19:24

    My first suggestion is to use a subquery to generate the list of item ID's and return items matching those item ID's. But this doesn't include the TagName in your result set. I'll submit a separate answer with another solution.

    SELECT i.ItemContent
    FROM item AS i
    WHERE i.id IN (
      SELECT it.ItemId
      FROM ItemTag AS it
        INNER JOIN tag AS t ON (t.id = it.TagId)
      WHERE t.TagName IN ('mysql', 'database', 'tags', 'tagging')
    );
    

    This is a non-correlated subquery, so a good SQL engine should factor it out and run it only once.

提交回复
热议问题