连接的等效子查询

时间:2017-11-03 22:48:08

标签: sql sql-server relational-database

我正在寻找一个实际上是

的答案

是否可以将每个Join重写为等效的子查询 我知道Subquery列不能选择外部查询。 我在sql server中运行查询

  select DISTINct A.*,B.ParentProductCategoryID from [SalesLT].[Product] as 
  A inner join [SalesLT].[ProductCategory] as B on 
  A.ProductCategoryID=B.ProductCategoryID

 select A.*
  from [SalesLT].[Product] as A
  where EXISTS(select B.ParentProductCategoryID  from [SalesLT].
 [ProductCategory] as B where A.ProductCategoryID=B.ProductCategoryID)

这两个查询都给了我输出293行,这是我所期望的。 现在问题是如何选择[SalesLT]。[ProductCategory]第二种情况中的列?

我是否需要在select子句中将此子查询联合起来才能使此列显示在输出中?

2 个答案:

答案 0 :(得分:1)

  

是否可以将每个Join重写为等效的子查询

不,因为连接可以1)删除行或2)乘以行

ex 1)

CREATE TABLE t1 (num int)
CREATE TABLE t2 (num int)

INSERT INTO t1 VALUES (1), (2), (3)
INSERT INTO t2 VALUES (2) ,(3)

SELECT * FROM t1 INNER JOIN t2 ON t1.num = t2.num

提供输出

t1num   t2num
2       2
3       3

删除了包含t1值1的行。这不会发生在子查询中。

ex 2)

CREATE TABLE t1 (num int)
CREATE TABLE t2 (num int)

INSERT INTO t1 VALUES (1), (2), (3)
INSERT INTO t2 VALUES (2) ,(3), (3), (3), (3)
SELECT t1.num AS t1num, t2.num as t2num FROM t1 INNER JOIN t2 ON t1.num = t2.num

提供输出

t1num   t2num
2       2
3       3
3       3
3       3
3       3

子查询不会更改要查询的表中的行数。

在你的例子中,你做了一个存在...这不会从第二个表中返回值。

这就是我要子查询的方式:

select A.*
      ,(SELECT B.ParentProductCategoryID
          FROM [SalesLT].[ProductCategory] B
         WHERE B.ProductCategoryID = A.ProductCategoryID) AS [2nd table ProductCategoryID]
  from [SalesLT].[Product] as A

答案 1 :(得分:0)

您可以使用

select A.*, 
(
   select B.ParentProductCategoryID  
   from [SalesLT].[ProductCategory] as B 
   where A.ProductCategoryID=B.ProductCategoryID
) ParentProductCategoryID  
from [SalesLT].[Product] as A
where EXISTS(select 1 
   from [SalesLT].[ProductCategory] as B 
   where A.ProductCategoryID=B.ProductCategoryID)

然而,我发现JOIN版本更加直观。

您无法在外部查询中使用EXISTS子查询中的任何数据。子查询的唯一目的是评估每个产品的EXISTS是真还是假。