给定 m2m 关系:items-categories我有三个表:
- 物品,
- 类别和
- items_categories包含对两者的引用
我想找到属于所有给定类别集的项目:
Find Item
belonging to a category in [1,3,6]
and belonging to a category in [7,8,4]
and belonging to a category in [12,66,42]
and ...
在 mySQL 中,我可以想到两种方法来完成此任务。
选项 A:内部连接:
SELECT id from items
INNER JOIN category c1 ON (item.id = c1.item_id)
INNER JOIN category c2 ON (item.id = c2.item_id)
INNER JOIN category c3 ON (item.id = c3.item_id)
...
WHERE
c1.category_id IN [1,3,6] AND
c2.category_id IN [7,8,4] AND
c3.category_id IN [12,66,42] AND
...;
选项 B:存在:
SELECT id from items
WHERE
EXISTS(SELECT category_id FROM category WHERE category.item_id = id AND category_id in [1,3,6] AND
EXISTS(SELECT category_id FROM category WHERE category.item_id = id AND category_id in [7,8,4] AND
EXISTS(SELECT category_id FROM category WHERE category.item_id = id AND category_id in [12,66,42] AND
...;
两种选择都有效。问题是:对于大型项目表,哪个是最快/最优化的?还是缺少 OPTION CI?