2017-11-03 149 views
0

我要尋找的答案實際上是等效子查詢的加入

是否有可能重寫每一個加入到相當於子查詢 我知道,子查詢列不能選擇外部查詢。 我在運行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子句中將此子查詢共同關聯以獲取此列以顯示在輸出中?

回答

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

+0

那麼對於表2中的每一列,如果我需要讓他們在reult我需要做的贊( 選擇B.ParentProductCategoryID 從[SalesLT] [ ProductCategory] ​​as B where A.ProductCategoryID = B.ProductCategoryID )ParentProductCategoryID –

1

是否有可能重寫每一個加入到相當於子查詢

沒有,因爲加入可以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

如果我不能從另一張表中選擇列,那麼我很難說他們可以互換使用。不是嗎? –