你能解决这个简单的SQL查询吗?

时间:2012-02-01 20:33:46

标签: mysql sql sql-match-all relational-division

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

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的摄像机: C1 C2 C3

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

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

3 个答案:

答案 0 :(得分: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是唯一的。

答案 1 :(得分: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的摄像机

答案 2 :(得分: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)