具有多个返回 EMPTY 的搜索参数的内连接表

问题描述 投票:0回答:1

下面有 3 个表格:

汽车
汽车功能
汽车规格(包含汽车 ID 和汽车功能 ID)

--Car Table
| ID |  name     |  ModelNo  |    Year    |
+----+-----------+-----------+------------+
|  1 |  VW Golf  |  1121     | 2010       | 
|  2 |  Dodge    |  3234     | 2016       |
|  3 |  Audi     |  5335     | 2394       | 
|  4 |  BMW      |  6567     | 9090       | 
|  5 |  Toyota   |  1221     | 9090       | 


--Car Feature Table
| ID |  Feature            | 
+----+---------------------+
|  1 |  ForkThickness      | 
|  2 |  OperatorProtection | 
|  3 |  RearTires          | 


--Car Spec table 
| ID |  CarId         |  Value               | CarFeatureId       |
+----+----------------+----------------------+--------------------+
|  1 |  1             |  1.50                | 1                  | 
|  2 |  1             |  Open Overhead       | 2                  |
|  3 |  1             |  Summer Tires        | 3                  |
|  4 |  2             |  1.30                | 1                  | 
|  5 |  2             |  Closed Overhead     | 2                  |
|  6 |  2             |  Winter Tires        | 3                  |
|  7 |  3             |  1.20                | 1                  | 
|  8 |  3             |  Closed Overhead     | 2                  |
|  9 |  3             |  Winter Tires        | 3                  |

所以如果我想显示所有汽车的 carId 和汽车名称 其中Feature.Feature = 'ForkThickness' 和相应的CarSpec.Value > 1.25

我可以让它返回正确的汽车,即汽车 ID 1 和 2。

SELECT DISTINCT ca.Id, ca.Name 
FROM Car AS ca
INNER JOIN CarSpec AS cs
    ON ca.id = cs.CarId    
INNER JOIN CarFeature AS cf
    ON cf.Id = cs.CarFeatureId    
WHERE cf.Feature = 'ForkThickness' AND cs.Value > 1.25

所以这有效。但是,当我尝试在搜索参数中包含更多功能时,例如:

WHERE Feature.Feature = 'ForkThickness' AND CarSpec.Value > 1.25
AND Feature.Feature = 'RearTires' AND CarSpec.Value = 'Summer Tires'

所以这个查询应该只返回 car 1 ...但它返回空。

我做错了什么吗?

任何帮助表示感谢,谢谢

sql sql-server inner-join
1个回答
0
投票

您的代码正在寻找同时具有Feature.Feature = ForkThickness AND Feature.Feature = RearTires 的东西。

where Feature.Feature = 'ForkThickness' and CarSpec.Value > 1.25
and Feature.Feature = 'RearTires' and CarSpec.Value = 'Summer Tires'

这可以与 OR 语句一起使用来查找选项,否则您可以删除双“Feature.Feature”参数/要求。

相反,将 AND 语句替换为 OR 语句:

WHERE (Feature.Feature = 'ForkThickness' AND CarSpec.Value > 1.25)
OR (Feature.Feature = 'RearTires' AND CarSpec.Value = 'Summer Tires')
© www.soinside.com 2019 - 2024. All rights reserved.