您可以创建新表?例如,您可以创建一个“词条”表,该表与prod和types表有许多关系。然后,你可以实现这样的逻辑:
-- get the set of all products which contain your terms
select p.id from prod p
inner join prod_terms pt on (p.id = pt.prod_id)
inner join terms t on (pt.term_id = t.id)
where t.term IN (<dynamically built list of terms>)
-- exclude products which contain terms not in your query
and not exists (
select pt.id from prod_terms pt2
inner join terms t2 on (pt.term_id = t.id)
where t2.term NOT IN (<dynamically built list of terms>)
) other_terms
然后,你可以为类型表做类似的事情。
注意事项:
- 我更熟悉的SQL Server, 的语法可能需要扭捏作 MySQL的
- 查询说明 一般的想法,但可能会导致一个缓慢 查询计划,所以一定要做perf 调整