假设这是一个销售相机的网站。这是我的实体(表):
Camera: A simple camera Feature: A feature like: 6mp, max resolution 1024x768,
事情是在相机和功能之间,我之间存在多对多关系,所以我有一张额外的桌子:
camera -> cameras_features -> feature
因此,查询很简单:
如何获得所有具有1,2和3功能的相机?
这就像构造一个位图索引。
您可以用来测试解决方案是否正确的数据
C1 has features 1,2,3 C2 has features 1,2,4 C3 has features 1,2
以下是查询和预期结果:
这是我所做的事情(它可以工作,但是确实很丑陋,不想使用它):
SELECT * FROM camera c WHERE c.id IN ( (SELECT c.id FROM camera c JOIN cameras_features f ON (c.id=f.camera_id) WHERE f.feature_id=1) q1 JOIN -- simple intersect (SELECT c.id FROM camera c JOIN cameras_features f ON (c.id=f.camera_id) WHERE f.feature_id=2) q2 JOIN ON (q1.id=q2.id) )
SELECT DISTINCT Camera.* FROM Camera c INNER JOIN cameras_features fc1 ON c.id = fc1.camera_id AND fc1.feature_id = 1 INNER JOIN cameras_features fc2 ON c.id = fc2.camera_id AND fc2.feature_id = 2
此处发生的情况是将摄像机筛选为功能1的摄像机,然后在该组中将摄像机筛选为功能2的摄像机。