SELECT * FROM items WHERE id IN
(SELECT DISTINCT item_id FROM item_tag WHERE
tag_id = tag1 OR tag_id = tag2 OR ...)
而标签就是
SELECT * FROM items WHERE
EXISTS (SELECT 1 FROM item_tag WHERE id = item_id AND tag_id = tag1)
AND EXISTS (SELECT 1 FROM item_tag WHERE id = item_id AND tag_id = tag2)
AND ...
不可否认,这对于大量的比较标记来说效率不高。如果要在内存中维护标记计数,可以使查询从不经常使用的标记开始,这样可以更快地计算 AND 序列。根据要匹配的标记的预期数量以及匹配其中任何一个标记的预期值,这可能是可行的解决方案,如果您要匹配20个标记,并期望某个随机项将匹配其中的15个,那么这对数据库来说仍然是一个沉重的负担。
Select distinct target from tags
where tag in ([your list of tags to search for here])
and target_type = [the table you're searching]
更新
根据您对 AND 条件的需求,上面的查询将变成这样的内容
select target
from (
select target, count(*) cnt
from tags
where tag in ([your list of tags to search for here])
and target_type = [the table you're searching]
)
where cnt = [number of tags being searched]