4

I am trying to write a query that will let me search if a patient has NOT received a medication. At first I thought that I could just do something like this:

INNER JOIN prescript p ON p.id = patient.id AND p.med_id NOT IN (5128)

Where p.id and patient.id signify the patient id, p.med_id refers to the medication id and 5128 is the medication being used in the query. The problem with this query is that if the patient has had other medications, those will show up. So if a patient has had medication 5128, but also another medication they will show up. But I only want to return a patient if they have not have that medication at all. The part that is tricky here is that I won't be able to know the patient id in any of this. So I need a solution that is similar to this:

INNER JOIN prescript p ON p.id = patient.id AND (SELECT med_id 
                                                 FROM prescript
                                                 WHERE id = p.pid) NOT IN (5128)

I was thinking that this might be possible if I could concatenate all of the med_id's into one string as well, but my problem with that is that I'm using a query builder so I'm limited to adding joins and adding wheres only. Aka I can't use DECLARE.

4

3 回答 3

3

所有未服药的患者 5128...

Select patient.*
from patient 
     left join prescript 
     on patient.id = prescript.patientid
     and prescript.medid = 5128
where 
     prescript.id is null

所有未服药患者 5128 或 3000

Select patient.*
from patient 
     left join prescript 
     on patient.id = prescript.patientid
     and prescript.medid in ( 5128 ,3000)
where 
     prescript.id is null

所有未服药患者 5128 和 3000

Select patient.*
from patient 
     left join prescript 
     on patient.id = prescript.patientid         
     and prescript.medid in ( 5128 ,3000)           
group by patient.id, patient.name
having COUNT(distinct medid)<>2
于 2012-10-10T14:28:27.007 回答
1

尝试left join

left join prescript p on p.id = patient.id and med_id = 5128 where p.id is null
于 2012-10-10T14:30:02.217 回答
1

您可以在语句中使用NOT EXISTS (SELECT * FROM prescript WHERE id = patient.id AND med_id = 5128)子句WHERE

如果您需要排除已使用至少一种药物的患者,那么您可以med_id IN (5128, ...)改用。

于 2012-10-10T14:46:55.477 回答