如何根据某些条件省略表连接?

时间:2016-03-09 09:59:29

标签: sql oracle

enter image description here

=======================

SELECT *
      FROM PRODUCT P
      JOIN PRODUCT_LOC PL
        ON P.PRODUCT_ID = PL.PRODUCT_ID

      JOIN PRODUCT_LOC_DEF PLD AND PL.LOC_ID = PLD.LOC_ID
      JOIN PRODUCT_CURRENT_LOC PCL
        ON PLD.LOC_ID = PCL.LOC_ID AND P.PRODUCT_ID = PCL.PRODUCT_ID

我应该如何修改查询以获得附加快照中给出的案例1和案例2中的预期结果?

优选的: 我正在寻找相同查询中的修改,而不是进行两次查询并将它们联合起来。

2 个答案:

答案 0 :(得分:0)

只需使用left join代替内部联接:

   SELECT *
     FROM PRODUCT P
LEFT JOIN PRODUCT_LOC PL ON P.PRODUCT_ID = PL.PRODUCT_ID
LEFT JOIN PRODUCT_LOC_DEF PLD AND PL.PRODUCT_LOC_ID = PLD.LOC_ID
LEFT JOIN PRODUCT_CURRENT_LOC PCL ON PLD.LOC_ID = PCL.LOC_ID

答案 1 :(得分:0)

你应该试试这个:

SELECT * FROM 
    PRODUCT p
INNER JOIN 
    PRODUCT_CURRENT_LOC pcl
ON
    p.PRODUCT_ID = pcl.PRODUCT_ID
INNER JOIN 
    PRODUCT_LOC pc
ON
    pc.LOC_ID = pcl.LOC_ID
UNION
SELECT * FROM 
    PRODUCT p
LEFT OUTER JOIN 
    PRODUCT_CURRENT_LOC pcl
ON
    p.PRODUCT_ID = pcl.PRODUCT_ID
    AND 
    pcl.PRODUCT_ID IS NULL
LEFT OUTER JOIN 
    PRODUCT_LOC pc
ON
    pc.LOC_ID = pcl.LOC_ID
    AND 
    pc.LOC_ID IS NULL