2013-11-25 111 views
1

我正在寫查詢以從兩張表,Products和ProductsImages中獲取數據。 我的查詢是:INNER JOIN with Data Exits條件

SELECT p.*, pi.* 
    FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId, ProductPrice 
    ORDER BY ProductId) AS row_number FROM Products) p 
    INNER JOIN (SELECT *, ROW_NUMBER() 
    OVER (PARTITION BY ProductId, ImageId,ImagePath 
    ORDER BY ImageId) AS row_number FROM ProductsImages) pi 
    ON p.ProductId = pi.ProductId 
    AND p.row_number = pi.row_number 
    Where p.ProductId='131'; 

我必須寫一個條件運行INNER JOIN是:實現INNER JOIN如果ProductsImages具有給出的productId 否則它應該運行沒有加入圖像。並只顯示圖像以外的產品細節。如果productsImages沒有任何圖像,此查詢不顯示產品詳細信息,如名稱和價格。
限制:我必須僅實現INNER JOIN。 請好心幫助我,指導我如何在這種情況下執行if-exits條件。感謝名單

+0

[這一個](http://stackoverflow.com/questions/9402922/inner-join-with-if-condition?rq=1)不符合我的問題。 – Sohail

回答

1

在你爲什麼不寫left join,

LEFT JOIN這種情況下不斷從產品表中的所有記錄,甚至與圖像表不匹配的記錄

SELECT p.*, pi.* 
    FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId, ProductPrice 
    ORDER BY ProductId) AS row_number FROM Products) p 
    LEFT OUTER JOIN (SELECT *, ROW_NUMBER() 
    OVER (PARTITION BY ProductId, ImageId,ImagePath 
    ORDER BY ImageId) AS row_number FROM ProductsImages) pi 
    ON p.ProductId = pi.ProductId 
    AND p.row_number = pi.row_number 
    Where p.ProductId='131'; 
+0

我的任務/任務/要求是去內部連接只..也在問題描述中編輯.. – Sohail

+0

返回左側加入。**可能它唯一的解決方案與較少的CPU成本。** Thnx求助。:) – Sohail

1

你可以試試內部查詢方式。例如:

SELECT p.*, (SELECT *, ROW_NUMBER() 
OVER (PARTITION BY ProductId, ImageId,ImagePath 
ORDER BY ImageId) AS row_number FROM ProductsImages pi WHERE p.ProductId = pi.ProductId AND p.row_number = pi.row_number) 
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId, ProductPrice 
ORDER BY ProductId) AS row_number FROM Products) p 
Where p.ProductId='131'; 

這裏沒有加入。 :(

+0

Thanx尋求幫助。我回到了左連接,因爲它給出了錯誤**「當EXISTS中沒有引入子查詢時,只能在選擇列表中指定一個表達式。」** – Sohail

+0

如果您可以在Sql Fiddle中附加代碼,那麼可能可以糾正查詢。當表格不在時,很難寫出完美的查詢。 ;) –