次のテーブルを持つ MySQL データベースがあります。
items | id, item
items_tags | id, item_name, item_id, tag_name, tag_id
tags | id, tag
ユーザーが任意のタグまたはタグの任意の組み合わせでアイテムを検索できるようにしたいと思います。私がやりたいことを示すためのデータの例を次に示します。
items:
id | item
-----------
1 | banana
2 | orange
3 | tomato
items_tags:
id | item_name | item_id | tag_name | tag_id
---------------------------------------------
1 | banana | 1 | yellow | 1
2 | banana | 1 | fruit | 2
3 | orange | 2 | orange | 3
4 | orange | 2 | fruit | 2
5 | tomato | 3 | red | 4
6 | tomato | 3 | vegetable| 5
tags:
id | tag
--------------
1 | yellow
2 | fruit
3 | orange
4 | red
5 | vegetable
"yellow" と "fruit" でタグ付けされたアイテムのみを返す (つまり、アイテムの行1 を返す) には、どのクエリを実行できますか?
ありがとう!
アップデート:
実用的な答えは次のとおりです。
SELECT *
FROM items
WHERE id IN (
SELECT item_id
FROM items_tags
WHERE tag_name IN ('yellow', 'fruit')
GROUP BY item_id
HAVING COUNT(*) = 2
)
助けてくれたchetanに感謝します!