如果连接表中缺少某些连接表中的所有记录,如何返回结果?

时间:2010-09-16 11:12:24

标签: sql

我有以下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中没有条目的产品的结果。我怎样才能适应它呢?

4 个答案:

答案 0 :(得分:2)

我认为实际发生的事情是忽略了vw_discounts中没有条目的记录 您应该使用左连接来加入折扣视图

答案 1 :(得分:1)

我认为您必须将vw_discounts上的内部连接更改为左连接

答案 2 :(得分:1)

以下加入:

LEFT JOIN tbl_discount

包括左表中的所有记录,即使右表中没有相应的记录。

所以,似乎问题不在于tbl_discount join,而是在vw_discounts join中。尝试将其更改为

LEFT JOIN vw_discounts

答案 3 :(得分: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