我有4個表SQL選擇其中不存在
branch target target_dept dept
-------- --------- ----------- --------
branch_id target_id target_id dept_id
branch_name branch_id dept_id dept_name
我想選擇與部門所有分支機構有關係 我在這裏查詢
select b.branch_id, b.branch_name,dept.dept_name
from branch b
left join target ptar on ptar.branch_id=b.branch_id
left join target_dept pdept on pdept.target_id=ptar.target_id
left join dept dept on pdept.dept_id=dept.dept_id
我得到了我想要得到與查詢。比方說像這樣的輸出(有在部門5個數據)
B001 | KUALA LUMPUR | DEPT1
B001 | KUALA LUMPUR | DEPT2
B002 | BALI | DEPT3
B002 | BALI | DEPT4
B002 | BALI | DEPT5
B003 | MANILLA |
,我想獲得與部門是說好的任何關係尚未分支,所以我用不存在這樣的查詢
select b.branch_id, b.branch_name,dept.dept_name
from branch b
left join target ptar on ptar.branch_id=b.branch_id
left join target_dept pdept on pdept.target_id=ptar.target_id
left join dept dept on not exists(select null where pdept.dept_id=dept.dept_id)
我想要得到的輸出是這樣的
B001 | KUALA LUMPUR | DEPT3
B001 | KUALA LUMPUR | DEPT4
B001 | KUALA LUMPUR | DEPT5
B002 | BALI | DEPT1
B002 | BALI | DEPT2
B003 | MANILLA | DEPT1
B003 | MANILLA | DEPT2
B003 | MANILLA | DEPT3
B003 | MANILLA | DEPT4
B003 | MANILLA | DEPT5
但我真的得到的輸出是不是我真正想要
添加樣品表數據及其預期結果。 (以及格式化文本。) – jarlh
請標記您的dbms –