等效子查询的加入

问题描述:

我要寻找的答案实际上是等效子查询的加入

是否有可能重写每一个加入到相当于子查询 我知道,子查询列不能选择外部查询。 我在运行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子句中将此子查询共同关联以获取此列以显示在输出中?

您可以使用

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是真或假。

+0

那么对于表2中的每一列,如果我需要让他们在reult我需要做的赞( 选择B.ParentProductCategoryID 从[SalesLT] [ ProductCategory] ​​as B where A.ProductCategoryID = B.ProductCategoryID )ParentProductCategoryID –

是否有可能重写每一个加入到相当于子查询

没有,因为加入可以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的行。这在子查询中不会发生。

前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 
+0

我问了这个问题,我从教授那里听说Join和子查询我们可以互换使用。但你的回答告诉我不同​​的东西,因为你说他们不是同样强大 –

+0

他们可以互换使用,但只有在一种情况下,我想。如果加入主键或“DISTINCT”值,则LEFT JOIN将给出相同的答案。这是因为连接条件对于LEFT JOIN是不同的 - 所以它不会乘以行;并且在任何一种情况下,如果它们在连接条件上不匹配,都会返回NULL。 – Zorkolot

+0

如果我不能从另一张表中选择列,那么我很难说他们可以互换使用。不是吗? –