简体   繁体   中英

Oracle SQL - Joins with condition

I'm sorry for asking these questions but I am really new and studying Oracle SQL for my university and I am having a hard time with a few things. Anyways, for this one, I am supposed to retrieve data from 2 different tables. One is from 'STAFF' and one is from 'BRANCH' I want the output to display the staff name (SNAME), the start date (STARTDATE) and the area (AREA). SNAME and STARTDATE are from the table 'STAFF', and the AREA is from the table 'Branch', how do I access that? Also, I ONLY want to display the names and start dates of those who are in the STOKE areea.

This is my code

SELECT SNAME, STARTDATE, BRANCH.AREA
    FROM STAFF CROSS JOIN BRANCH
        WHERE STAFF.BRANCHID = 20;

Note: The STAFF.BRANCHID = 20 is because the area 'STOKE' has a BRANCHID of 20.

This is what I get:

SNAME      STARTDATE AREA         
---------- --------- -------------
SMITH      15-NOV-00 ECCLESHALL   
JONES      02-MAR-01 ECCLESHALL   
SONG       03-JAN-02 ECCLESHALL   
SMITH      15-NOV-00 STOKE              
SONG       03-JAN-02 STOKE        
SMITH      15-NOV-00 STAFFORD 

As you can see, the WHERE clause is not working because it outputs every area instead of stoke only.

I know I am supposed to use the JOIN function but I don't get which one and why, any useful links would be appreciated :)

Thank you

You need to use the INNER JOIN and proper join condition as follows:

SELECT S.SNAME, S.STARTDATE, B.AREA
  FROM STAFF S INNER JOIN BRANCH B
    ON S.BRANCHID = B.BRANCHID
 WHERE S.AREA = 'STOKE';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM