左连接不使用3个表的左连接

时间:2016-03-20 14:18:38

标签: sql sql-server join left-join inner-join

我必须使用left join从3个表中获取所有数据。我使用和不使用left join做到了这一点。但我的老师问另一个仅使用inner join的解决方案。我找不到解决方案请给出一些建议。以下是表格:

enter image description here

结果应如下所示:

enter image description here

使用left join解决方案:

SELECT O.*,C.CUST_CODE,C.CUST_NAME,P.PART_CODE,P.PART_NAME 
FROM ORDERS O
LEFT OUTER JOIN PART P ON P.PART_ID = O.PART_ID
LEFT OUTER JOIN CUSTOMER C ON C.CUST_ID = O.CUST_ID

没有left join解决方案:

SELECT O.*,
(SELECT C.CUST_CODE FROM CUSTOMER C WHERE C.CUST_ID=O.CUST_ID) AS CUST_CODE,
(SELECT C.CUST_NAME FROM CUSTOMER C WHERE C.CUST_ID=O.CUST_ID) AS CUST_NAME,
(SELECT P.PART_CODE FROM PART P WHERE P.PART_ID = O.PART_ID ) AS PART_CODE,
(SELECT P.PART_NAME FROM PART P WHERE P.PART_ID = O.PART_ID ) AS PART_NAME
FROM ORDERS O

2 个答案:

答案 0 :(得分:3)

以下是一种仅使用INNER JOIN并且不在任何地方使用LEFT JOIN的方法。它使用INNER JOIN而不是LEFT JOIN从您的原始查询开始,然后在结果集中添加从获取所有表的内积中丢失的部分。

SELECT t.* FROM
(
    SELECT O.ORDER_ID, O.ORDER_DATE, C.CUST_CODE, C.CUST_NAME, P.PART_CODE, P.PART_NAME 
    FROM ORDERS O
    INNER JOIN PART P
        ON P.PART_ID = O.PART_ID
    INNER JOIN CUSTOMER C
        ON C.CUST_ID = O.CUST_ID
    UNION
    SELECT O.ORDER_ID, O.ORDER_DATE, NULL AS CUST_CODE, NULL AS CUST_NAME, P.PART_CODE,
        P.PART_NAME 
    FROM ORDERS O
    INNER JOIN PART P
        ON P.PART_ID = O.PART_ID
    WHERE O.CUST_ID NOT IN (SELECT C.CUST_ID FROM CUSTOMER C)
        OR O.CUST_ID IS NULL
    UNION
    SELECT O.ORDER_ID, O.ORDER_DATE, C.CUST_CODE, C.CUST_NAME, NULL AS PART_CODE,
        NULL AS PART_NAME 
    FROM ORDERS O
    INNER JOIN CUSTOMER C
        ON C.CUST_ID = O.CUST_ID
    WHERE O.PART_ID NOT IN (SELECT P.PART_ID FROM PART P)
        OR O.PART_ID IS NULL
    UNION
    SELECT O.ORDER_ID, O.ORDER_DATE, NULL AS CUST_CODE, NULL AS CUST_NAME,
        NULL AS PART_CODE, NULL AS PART_NAME
    FROM ORDERS O
    WHERE (O.CUST_ID NOT IN (SELECT C.CUST_ID FROM CUSTOMER C) AND
           O.PART_ID NOT IN (SELECT P.PART_ID FROM PART P)) OR
           (O.CUST_ID IS NULL AND O.PART_ID IS NULL)
) t
ORDER BY t.ORDER_ID ASC

请点击以下链接查看有效的演示:

SQLFiddle

答案 1 :(得分:1)

这在现实生活中毫无意义,但我理解它在SQL课程中的意义。你有一位好老师。

试试这个

SELECT * FROM
(   
    SELECT O.*,C.CUST_CODE,C.CUST_NAME,P.PART_CODE,P.PART_NAME 
    FROM ORDERS O
    INNER JOIN PART P ON P.PART_ID = O.PART_ID
    INNER JOIN CUSTOMER C ON C.CUST_ID = O.CUST_ID

    UNION

    SELECT O.*,NULL,NULL,P.PART_CODE,P.PART_NAME 
    FROM ORDERS O
    INNER JOIN PART P ON P.PART_ID = O.PART_ID
    WHERE O.CUST_ID IS NULL

    UNION

    SELECT O.*,C.CUST_CODE,C.CUST_NAME,NULL, NULL
    FROM ORDERS O
    INNER JOIN CUSTOMER C ON C.CUST_ID = O.CUST_ID
    WHERE O.PART_ID IS NULL

    UNION

    SELECT O.*,NULL,NULL,NULL, NULL
    FROM ORDERS O
    WHERE O.PART_ID IS NULL AND O.CUST_ID IS NULL   

)   T

ORDER BY ORDER_ID