你能解决这个简单的 SQL 查询吗?
假设这是一个销售相机的网站。这是我的实体(表):
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)
)
Suppose it's a website that sells photo cameras. Here are my entities (tables):
Camera: A simple camera
Feature: A feature like: 6mp, max resolution 1024x768,
The thing is between cameras and feature i've got a Many to Many relationship, so i have an extra table:
camera -> cameras_features -> feature
So, the query is simple:
How to get all the cameras that have the feature 1,2 and 3?
It's like constructing a bitmap index.
Data you can use to test if the solution is ok
C1 has features 1,2,3
C2 has features 1,2,4
C3 has features 1,2
Here are querys and the expected result:
- Show all the cameras which have feature 1,2 and 3: C1
- Show all the cameras which have feature 1,2 and 4: C2
- Show all the cameras which have feature 1 and 2: C1, C2 and C3
Here is what i did (it works, but it's really ugly, don't want to use it):
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)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
3
是(1,2,3)
中的特征数量。并假设(camera_id,feature_id)
在camera_features
中是唯一的。3
is the number of features in(1,2,3)
. And assuming(camera_id,feature_id)
is unique incamera_features
.这里发生的情况是,摄像机将被过滤到具有功能 1 的摄像机,然后在该组中,摄像机将被过滤到具有功能 2 的摄像机
What is happening here is that cameras will be filtered down to cameras with feature 1, then within this group, the cameras are gonna be filtered down to the ones with feature 2
通过将搜索值放入表中,这是最容易概括的......
This is easiest to generalise by putting the search values into a table...