簡體   English   中英

聯接的等效子查詢

[英]Equivalent Subquery for a Join

我正在尋找實際上是一個答案

是否有可能重寫每個聯接到等效的子查詢,我知道不能選擇外部查詢的子查詢列。 我在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子句中關聯此子查詢,以使此列顯示在輸出中?

是否有可能重寫每個聯接到等效的子查詢

否,因為聯接可以1)刪除行或2)乘以行

例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

你可能會用

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是對還是錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM