我有以下表结构。
表:车辆
+--------+--------+-------+----------+
| Diesel | Petrol | LPG | Hybrid |
+--------+--------+-------+----------+
| yes | no | no | no |
| no | yes | no | no |
| no | no | yes | no |
| no | no | no | yes |
+--------+--------+-------+----------+
我想从存储过程参数中检索基于列的第一个字符的记录集。到目前为止我已经尝试过以下查询。
我的@FuelType参数值看起来像'D,P,L'。
Select * from Vehicle
Where (Diesel = Case When CharIndex('D', @FuelType) > 0 Then 'yes'
Else 'no' End)
Or (Petrol = Case When CharIndex('P', @FuelType) > 0 Then 'yes'
Else 'no' End)
Or (LPG = Case When CharIndex('L', @FuelType) > 0 Then 'yes'
Else 'no' End)
Or (Hybrid = Case When CharIndex('H', @FuelType) > 0 Then 'yes'
Else 'no' End)
是否有可能优化上述查询?
答案 0 :(得分:0)
我不了解查询,但肯定有机会更好地规范架构设计。您在车辆和燃料类型之间存在多对多关系。您应该使用联结表解决此问题。
您的查询可能会变成:
SELECT v.*
FROM Vehicle v
INNER JOIN Vehicle_FuelType_Xref vftx
ON v.VehicleID = vftx.VehicleID
INNER JOIN Fuel_Type ft
ON vftx.FuelTypeID = ft.FuelTypeID
WHERE ft.FuelType IN ('Diesel', 'Petrol', 'LPG');