【问题标题】:SQL Server avoid repeat same joinsSQL Server 避免重复相同的连接
【发布时间】:2023-03-16 19:10:02
【问题描述】:

我正在执行下面的查询,我多次重复相同的连接,有更好的方法吗? (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
...

谢谢!!

【问题讨论】:

  • 同一个表的多个连接是很常见的。您可以通过将 SalesFrutes 和 SalesVegetable 表联合在一起来简化事情。将它们分成两个表似乎是一个奇怪的设计选择。
  • 我同意这一点,如果你加入一张sales 的桌子,你有一个type 来表明卖了什么;拥有具有基本相同架构和数据的单独表是您的根本问题。
  • 此销售...仅用于示例,在我的真实场景中,它们在信息上并不等效。
  • 建议的 cmets 和答案将适用于您提供的信息,而不是您未提供的信息。

标签: sql sql-server join


【解决方案1】:

因此,根据提供的信息,我会建议以下使用cte 来“修复”数据模型并使编写查询更容易。

由于您说您的实际场景与提供的信息不同,但它可能对您不起作用,但如果您说 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

【讨论】:

  • 我会尽量把所有Sales常用栏都做union,谢谢
猜你喜欢
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-30
  • 2015-12-06
  • 1970-01-01
  • 2013-12-18
相关资源
最近更新 更多