私は3つのテーブル、、、books
およびtags
(taggings
)を持っていますbooks-xref-tags
:
books
id | title | author
1 | Blink | Malcolm Gladwell
2 | 1984 | George Orwell
taggings
book_id | tag_id
1 | 1
1 | 2
2 | 1
2 | 3
tags
id | name
1 | interesting
2 | nonfiction
3 | fiction
「おもしろい」と「フィクション」の両方のタグが付いた本をすべて検索したいのですが。私が思いついた最高のものは
select books.* from books, taggings, tags
where taggings.book_id = books.id
and taggings.tag_id = tag.id
and tag.name = "interesting"
intersect
select books.* from books, taggings, tags
where taggings.book_id = books.id
and taggings.tag_id = tag.id
and tag.name = "fiction"
それはうまくいくようですが、行またはタグの数のいずれかでどのようにスケーリングするかはわかりません。つまり、数百冊の本、数百のタグ、数千のタグを追加するとどうなりますか?検索が「「面白い」と「フィクション」と「水生」と「石工」になるとどうなりますか?
SQLで直接クエリを実行するより良い方法がない場合は、別のアプローチを考えています。
- 最初のタグが付いたすべての本と、それらの本のすべてのタグを選択します
- すべてのタグが照会されていないものをリストから削除します