Pregunta

I have 2 tables, the first one is MASTER_TABLE with fields ID, STATUS_CODE, STATUS_SUBCODE, SUBJECT_CODE, SUBJECT_SUBCODE and the second table is CODE_TABLE which has the unique description for every combination of a code and subcode. It has the following fields CODE, SUBCODE and DESCRIPTION

How to write a query to retrieve the ID, STATUS and SUBJECT , for example for every combination of STATUS_CODE and STATUS_SUBCODE in MASTER_TABLE I have to get the STATUS value in CODE_TABLE, similarly I have to do the same thing for SUBJECT

¿Fue útil?

Solución

You must join twice to CODE_TABLE - once for each type of look-up, so to distinguish the rows from eachother, you must alias at least one (but usually one would alias both, as below):

select 
  mt.ID,
  ct1.DESCRIPTION as STATUS
  ct2.DESCRIPTION as SUBJECT
from MASTER_TABLE mt
left join CODE_TABLE ct1 
    on ct1.CODE = mt.STATUS_CODE and ct1.SUBCODE = mt.STATUS_SUBCODE
left join CODE_TABLE ct2
    on ct2.CODE = mt.SUBJECT_CODE and ct2.SUBCODE = mt.SUBJECT_SUBCODE

I have made the joins left joins in case data is missing from CODE_TABLE, in which case this query would produce a null for the corresponding description.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top