ahairshi
ahairshi

Reputation: 381

Oracle: Subquery - Another way?

This is regarding query in Oracle.

I have one master table, which stores id, name and description of the project along with the code(s). The table I used, has more than 4 codes to describe health, status, and etc. The codes and their descriptions are in the same table , say generic table.

When I do select query on the main table, I have to use subqueries to get the descriptions of the code from the generic table. The query gets larger as I have to do Subquery for each and every codes.

Is there any other way to get the output?

Master Table:
-------
Id: 100

Name:

Desc:
Health: H1

Status: S1

code3: c1

.........

........
........


Generic Table:
--------------
Code Description

H1   red

H2   green

..   ......

S1  Critical

..  ........

..  ........

c1  ........
............
............

For the id 100, I used the query,

    SELECT  ID,
    PROJ_NAME,
    PROJ_DESC,
         (SELECT Description FROM generic WHERE id = P.Health) Health,
         (SELECT Description FROM generic WHERE id = P.status) Code2,
         (SELECT Description FROM generic WHERE id = P.Code3) Code3,
    FROM master P
    WHERE ID in (100);

Upvotes: 0

Views: 158

Answers (1)

John Woo
John Woo

Reputation: 263703

you can use JOIN instead of SUBQUERY

SELECT  ID,
        PROJ_NAME,
        PROJ_DESC,
        a.Description AS Health,
        b.Description AS Code2,
        c.Description AS Code3
FROM    master P
        INNER JOIN generic a
            ON a.id = P.Health
        LEFT JOIN generic b
            ON b.id = P.status
        LEFT JOIN generic c
            ON c.id = P.HCode3
WHERE p.id = 100

Upvotes: 2

Related Questions