我有3个表有外键 ACCOUNT_NO ,第一个表是 CREDIT_LIST ,其中包含从银行取得的所有积分,第二个表是 CUSTOMERS 其中包含客户信息,最后一个是 ACCOUNTS ,其中包含有关帐户本身的所有信息。当我尝试选择
时SELECT
B.CUSTOMER_NO AS CUSTOMER_NO,
B.CREDIT_TYPE AS CREDIT_TYPE,
B.ACCOUNT_NO AS CREDIT_ACCOUNT_NUMBER,
A.BRANCH_CODE AS BRANCH_CODE,
C.EXTERNAL_ACCOUNT_NO AS EXTERNAL_ACCOUNT_NUMBER
FROM
CREDIT_LIST B,
CUSTOMERS A,
ACCOUNTS C
WHERE
B.STATUS = 'A' -- ACTIVE
AND A.CUSTOMER_NO = B.CUSTOMER_NO
AND C.ACCOUNT_NO = B.ACCOUNT_NO
;
我的结果为零,因为 ACCOUNTS 中没有EXTERNAL_ACCOUNT_NO
且c.account_no = b.account_no
。问题是我想显示信息,即使没有EXTERNAL_ACCOUNT_NO
并填写为null,例如:
| CUSTOMER_NO | CREDIT_TYPE | CREDIT_ACCOUNT_NUMBER | BRANCH_CODE | EXTERNAL_ACCOUNT_NUMBER
+-------------+-------------+-----------------------+-------------+------------------------
| 1 | some_type | 123456 | 01 |
| 2 | some_type | 654321 | 01 | 111111111111
我觉得这非常愚蠢,但无法弄清楚我到底做错了什么
答案 0 :(得分:1)
我认为,这就是你需要的
SELECT
B.CUSTOMER_NO AS CUSTOMER_NO,
B.CREDIT_TYPE AS CREDIT_TYPE,
B.ACCOUNT_NO AS CREDIT_ACCOUNT_NUMBER,
A.BRANCH_CODE AS BRANCH_CODE,
C.EXTERNAL_ACCOUNT_NO AS EXTERNAL_ACCOUNT_NUMBER
FROM
CREDIT_LIST B
JOIN CUSTOMERS A on A.CUSTOMER_NO = B.CUSTOMER_NO
LEFT JOIN ACCOUNTS C on C.ACCOUNT_NO = B.ACCOUNT_NO
WHERE
B.STATUS = 'A' -- ACTIVE
;
左连接将确保您从A和B获取详细信息,即使C中没有可用数据。
此外AS
是多余的,并非真正需要,您只需在查询的第4行中编写B.ACCOUNT_NO CREDIT_ACCOUNT_NUMBER
即可。
左外连接 - Reference
不建议,但是,如果有原因,您需要使用旧语法,以下是您需要的
SELECT
B.CUSTOMER_NO AS CUSTOMER_NO,
B.CREDIT_TYPE AS CREDIT_TYPE,
B.ACCOUNT_NO AS CREDIT_ACCOUNT_NUMBER,
A.BRANCH_CODE AS BRANCH_CODE,
C.EXTERNAL_ACCOUNT_NO AS EXTERNAL_ACCOUNT_NUMBER
FROM
CREDIT_LIST B,
CUSTOMERS A,
ACCOUNTS C
WHERE
B.STATUS = 'A' -- ACTIVE
AND A.CUSTOMER_NO = B.CUSTOMER_NO
AND C.ACCOUNT_NO(+) = B.ACCOUNT_NO -- (+) will do a outer join for you
;