sql - SQL Server 避免重复相同的连接
问题描述
我正在执行下面的查询,我多次重复相同的连接,有更好的方法吗?(SQL Server Azure)
前任。
Table: [Customer]
[Id_Customer] | [CustomerName]
1 | Tomy
...
Table: [Store]
[Id_Store] | [StoreName]
1 | SuperMarket
2 | BestPrice
...
Table: [SalesFrutes]
[Id_SalesFrutes] | [FruteName] | [Fk_Id_Customer] | [Fk_Id_Store]
1 | Orange | 1 | 1
...
Table: [SalesVegetable]
[Id_SalesVegetable] | [VegetableName] | [Fk_Id_Customer] | [Fk_Id_Store]
1 | Pea | 1 | 2
...
Select * From [Customer] as C
left join [SalesFrutes] as SF on SF.[Fk_Id_Customer] = C.[Id_Customer]
left join [SalesVegetable] as SV on SV.[Fk_Id_Customer] = C.[Id_Customer]
left join [Store] as S1 on S1.[Id_Store] = SF.[Fk_Id_Store]
left join [Store] as S2 on S1.[Id_Store] = SV.[Fk_Id_Store]
在我的真实案例中,我有许多 [Sales...] 要与 [Customer] 联接,还有许多其他类似于 [Store] 的表要加入每个 [Sales...]。因此,它开始大量增加重复连接的数量。有更好的方法吗?
额外的问题:我也喜欢在同一列下有 FruteName、VegetableName、StoreName 和每个 Food 表名称。
The Expected Result is:
[CustomerName] | [FoodName] | [SalesTableName] | [StoreName]
Tomy | Orange | SalesFrute | SuperMarket
Tomy | Pea | SalesVegetable | BestPrice
...
谢谢!!
解决方案
因此,根据提供的信息,我会建议以下内容,使用 acte
来“修复”数据模型并使编写查询更容易。
由于您说您的实际场景与提供的信息不同,它可能对您不起作用,但如果您说 80% 共享列仍然适用,您可以只使用与合并数据集相关的占位符/空值并且仍然最小化连接的数量,例如到你的store
表。
with allSales as (
select Id_SalesFrutes as Id, FruitName as FoodName, 'Fruit' as SaleType, Fk_Id_customer as Id_customer, Fk_Id_Store as Id_Store
from SalesFruits
union all
select Id_SalesVegetable, VegetableName, 'Vegetable', Fk_Id_customer, Fk_Id_Store
from SalesVegetable
union all... etc
)
select c.CustomerName, s.FoodName, s.SaleType, st.StoreName
from Customer c
join allSales s on s.Id_customer=c.Id_customer
join Store st on st.Id_Store=s.Id_Store
推荐阅读
- javascript - 选择类别后调整大小
- c# - 如何使用从 C# 代码传递到 C++ 代码 (dll) 的字符串并带有 AccessViolationException
- javascript - 在分布式环境中拆分数组以找到两个子数组之和之间的最小差异
- angular - 在包装表中使用 Angular Material 表 mat-text-column
- python - 如何匹配 json 汤中的确切单词?
- python - 如何使用 pyinstaller 在应用程序构建中加载插件?
- flutter - 实施 map_view 时无法继续
- reactjs - 按具有 children 属性的行数据分组
- java - Camunda 外部客户端:TASK/CLIENT-02002 为请求建立连接时出现异常
- python - 根据其他数据框中的数据填充新数据框