2010-09-16 89 views
0

我有以下SQL查詢如何在連接表查詢中的一個連接表中缺少結果時返回結果?

SELECT tbl_product.prod_id, 
     ISNULL (prod_code, '')      AS prod_code, 
     ISNULL (prod_category, '')     AS prod_category, 
     ISNULL(prod_title, '')      AS prod_title, 
     ISNULL(prod_price, 0.0)      AS prod_price, 
     ISNULL(tbl_product.prod_sales_price, 0.0) AS prod_sales_price, 
     ISNULL(prod_desc, '')      AS prod_desc, 
     ISNULL(prod_location, '')     AS prod_location, 
     brand_title, 
     pd_discount = CASE 
         WHEN P_Discount > 0 THEN vw_discounts.P_Discount 
         WHEN B_discount > 0 THEN vw_discounts.B_discount 
         WHEN D_Discount > 0 THEN vw_discounts.D_Discount 
         ELSE 0.00 
        END, 
     ISNULL((SELECT image_path 
       FROM tbl_image 
       WHERE tbl_image.prod_id = tbl_product.prod_id 
         AND image_primary = 1), '''') AS MainImage, 
     ISNULL(prod_pick_from_store, 0)    AS prod_pick_from_store 
FROM tbl_product 
     LEFT JOIN tbl_brand 
     ON tbl_brand.brand_id = tbl_product.brand_id 
     LEFT JOIN tbl_discount 
     ON Pd_ProdId = tbl_product.Prod_id 
     INNER JOIN vw_discounts 
     ON Pd_ProdId = vw_discounts.prod_id 
WHERE tbl_product.prod_id > 270 
     AND tbl_product.prod_id < 290 

目前該查詢不具有在tbl_discount入門產品不返回結果。我如何適應它,以便它呢?

回答

2

我認爲實際情況是,沒有在vw_discounts一個條目記錄被忽略 你應該使用左連接加入與折扣查看過

+0

可愛,這就是它,非常感謝! – fearoffours 2010-09-16 11:50:32

1

我認爲你將不得不改變內在vw_discounts加入爲左連接

1

以下連接:

LEFT JOIN tbl_discount 

包括來自左表(S)的所有記錄,即使有右表中沒有相應的記錄。

所以,似乎問題不在於tbl_discount連接,而是在vw_discounts連接。嘗試將其更改爲

LEFT JOIN vw_discounts 
+0

我認爲你的倒數第二句話有一個錯字 - 請你檢查一下嗎? – fearoffours 2010-09-16 11:35:40

+0

對不起,修正:) – Kel 2010-09-16 17:06:26

0

您需要更改下面連接到外部連接

LEFT JOIN tbl_brand ON tbl_brand.brand_id = tbl_product.brand_id LEFT JOIN tbl_discount ON Pd_ProdId = tbl_product.Prod_id INNER JOIN vw_discounts ON Pd_ProdId = vw_discounts.prod_id

相關問題