2

假设它是一个销售照片相机的网站。这是我的实体(表格):

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

以下是查询和预期结果:

  • 显示所有具有功能 1,2 和 3 的相机: C1
  • 显示所有具有功能 1,2 和 4 的相机: C2
  • 显示所有具有功能 1 和 2 的相机: C1C2C3

这是我所做的(它有效,但它真的很难看,不想使用它):

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)
)
4

3 回答 3

5
SELECT camera.id
FROM camera JOIN camera_features ON camera.id=camera_features.camera_id
GROUP BY camera.id
HAVING sum(camera_features.feature_id IN (1,2,3))=3

3是 中的特征数(1,2,3)。并且假设(camera_id,feature_id)camera_features.

于 2012-02-01T20:38:18.317 回答
3
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 的相机

于 2012-02-01T20:38:39.477 回答
1

通过将搜索值放入表中,这是最容易概括的...

INSERT INTO search SELECT 1
         UNION ALL SELECT 2
         UNION ALL SELECT 3

SELECT
  camera_features.camera_id
FROM
  camera_features
INNER JOIN
  search
    ON search.id = camera_features.feature_id
GROUP BY
  camera_features.camera_id
HAVING
  COUNT(DISTINCT camera_features.feature_id) = (SELECT COUNT(DISTINCT id) FROM search)
于 2012-02-01T20:39:45.343 回答