问题
I have the following 4 tables mentioned below and trying to extract the value ACC_NUMBER from sub query, Please help me with optimized correct syntax
ACCOUNT TABLE
-------------------------
|ACC_NUMBER | ACC_NAME|
-------------------------
ACCOUNT_DETAILS TABLE
---------------------------------
|ACC_NUMBER |DEAL_NUMBER|DEAL_TYPE|
---------------------------------
DEALS TABLE
------------------------------------
|DEAL_NUMBER |DEAL_TYPE|DEP_NUMBER |
------------------------------------
DEPARTMENT TABLE
------------------------
|DEP_NUMBER | DEP_NAME |
------------------------
SELECT
D.DEAL_NUMBER,
D.D_TYPE,
DP.DEPARTMENT_NUMBER
FROM
DEALS D , DEPARTMENT DP
WHERE
D.DEP_NUMBER = DP.DEP_NUMBER
AND D.DEAL_NUMBER NOT IN
(SELECT ACD.DEAL_NUMBER
FROM ACCOUNT_DETAILS ACD, ACCOUNT AC
WHERE AC.ACC_NUMBER = ACD.ACC_NUMBER
AND DEAL_TYPE = 'XXXX'
AND ACD.DEAL_NUMBER = D.DEAL_NUMBER)
回答1:
Hi, If you are using
D.DEAL_NUMBER NOT IN
that means that records join is not present in ACCOUNT and ACCOUNT_DETAILS table, You will never get ACC_NUMBER for that particular deals?If you are ready to do some alteration in the current syntax, You can play with joins to get ACC_NUMBER in your query result:
Example:
SELECT
D.DEAL_NUMBER,
D.D_TYPE,
ACD.ACC_NUMBER,
DP.DEPARTMENT_NUMBER
FROM
DEALS D
join DEPARTMENT DP
on D.DEP_NUMBER = DP.DEP_NUMBER
left join ACCOUNT_DETAILS ACD
on ACD.DEAL_NUMBER = D.DEAL_NUMBER
join ACCOUNT AC AC.ACC_NUMBER = ACD.ACC_NUMBER
WHERE DEAL_TYPE = 'XXXX'
AND ACD.DEAL_NUMBER = D.DEAL_NUMBER
来源:https://stackoverflow.com/questions/45369874/how-to-select-the-value-from-sub-query-result