Your problem is how you are using the conditions AND
and OR
. The precedence indicates that the AND
and the OR
are evaluated at the end, I will rewrite it with parentheses so that it is clear to you why you are getting those results:
select *
from paciente pc
inner join persona per
on per.dni=pc.dni
inner join det_pac_tra dp
on dp.dni=pc.dni
where ( pc.cod_centro_salud='3'
and pc.cod_situacion='1'
and dp.frecuencia_fase1 = '1')
or dp.frecuencia_fase2='2';
In this case, if dp.frecuencia_fase2='2'
is true, then all WHERE
is true.
You can rewrite it in the following way:
select *
from paciente pc
inner join persona per
on per.dni=pc.dni
inner join det_pac_tra dp
on dp.dni=pc.dni
where pc.cod_centro_salud='3'
and pc.cod_situacion='1'
and (dp.frecuencia_fase1 = '1'
or dp.frecuencia_fase2='2');
Or what is simplest would be to use IN
:
select *
from paciente pc
inner join persona per
on per.dni=pc.dni
inner join det_pac_tra dp
on dp.dni=pc.dni
where pc.cod_centro_salud='3'
and pc.cod_situacion='1'
and dp.frecuencia_fase1 in ('1','2');