0

So I've been given a task where i should present the following:

ID, LNAME, FNAME, MNAME, BIRTH_DATE, RELG_CODE, NAT_CODE, PT_STATUS, RM_NO, DTTM_ADM

The tables are:

HISR_CODES, PASR_NAMES, PASR_PROFILE, PAST_PATIENT_ADM

--Viewing them using DESC--

So while I viewed them, I was told that the ID on these tables are the same. So what I did so far in the coding (I'll finish the rest but I need to make sure this works first):

SELECT
    A.ID,
    A.LNAME,
    A.FNAME,
    A.MNAME,
    A.BIRTH_DATE,
    C.RELG_CODE,
    C.NAT_CODE,
    B.PT_STATUS,
    B.RM_NO,
    B.DTTM_ADM
FROM
    PASR_NAMES A,
    PASR_PROFILE B,
    PAST_PATIENT_ADM C,
    HISR_CODES D

WHERE
    A.ID = B.ID
AND
    B.ID = C.ID
AND
    C.ID = D.ID

Is there a way to tell that all of the ID's from the tables are the same? A simpler code than going on like this:

WHERE
        A.ID = B.ID
    AND
        B.ID = C.ID
    AND
        C.ID = D.ID

Or is JOIN - ON the only option for this?

Sebas
  • 21,192
  • 9
  • 55
  • 109

2 Answers2

2

You can use NATURAL JOIN as below:

SELECT
    A.ID,
    A.LNAME,
    A.FNAME,
    A.MNAME,
    A.BIRTH_DATE,
    C.RELG_CODE,
    C.NAT_CODE,
    B.PT_STATUS,
    B.RM_NO,
    B.DTTM_ADM
FROM
    PASR_NAMES A
    NATURAL JOIN PASR_PROFILE B
    NATURAL JOIN PAST_PATIENT_ADM C
    NATURAL JOIN HISR_CODES D;

From Oracle Reference, "A natural join is based on all columns in the two tables that have the same name." So, there is a chance that the joins happen based on other columns as well. Therefore, it is recommended that you still use the INNER JOIN syntax and explicitly specify the JOIN columns.

References:

NATURAL JOIN on Oracle® Database SQL Language Reference

Related SO question

Community
  • 1
  • 1
Joseph B
  • 5,519
  • 1
  • 15
  • 19
0

Use the proper join syntax:

FROM PASR_NAMES A JOIN
     PASR_PROFILE B
     ON A.ID = B.ID JOIN
     PAST_PATIENT_ADM C
     ON B.ID = C.ID JOIn
     HISR_CODES D
     ON C.ID = D.ID

Or:

FROM PASR_NAMES A JOIN
     PASR_PROFILE B
     USING (ID) JOIN
     PAST_PATIENT_ADM C
     USING (ID)
     HISR_CODES D
     USING (ID)

I would discourage you from using the natural join. It might seem like the right thing at first. However, the semantics of the query are highly dependent on the structure of the tables. If columns are renamed, removed, or added, the query might still work but produce highly unexpected results.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786