首页 > 解决方案 > 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
...

谢谢!!

标签: sqlsql-serverjoin

解决方案


因此,根据提供的信息,我会建议以下内容,使用 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

推荐阅读