1

我有三张桌子:

产品

  • 产品_ID
  • 姓名
  • 描述
  • 价格

供应商

  • 供应商_ID
  • 姓名
  • 地点

产品供应商

  • 产品_ID
  • 供应商_ID

ProductSupplier是联结表,而不是多对多关系。

我需要创建一个SELECT返回两列的语句:产品的名称和价格(不是产品 ID),但前提Supplier是产品位于澳大利亚。供应商的位置无法显示在结果中。

如果没有连接表,我会知道如何做到这一点,但这让我很困惑。

4

2 回答 2

1

如果你可以避免select distinct(和count(distinct)),那么这是一个好主意。它们会产生额外的删除重复项的开销。

因此,最好的方法是在where子句中进行过滤,使用inor exists

select p.Name, p.Price
from Product p
where exists (select 1
              from ProductSupplier ps inner join
                   Supplier s
                   on s.Supplier_ID = ps.Supplier_ID
              where ps.Product_ID = p.Product_ID and s.Location = 'Australia'
             );

这应该有最好的执行计划。

于 2018-09-16T12:19:00.247 回答
-1

以下 sql 语句将返回所有产品至少有供应商位于澳大利亚

select distinct p.Name,p.Price
from Product  p
inner join ProductSupplier  ps on ps.Product_ID = p.Product_ID
inner join Supplier  s on s.Supplier_ID = ps.Supplier_ID
where s.Location = 'Australia'
于 2018-09-16T04:24:18.467 回答