TSQL IN 和 NOT IN

TSQL IN and NOT IN

我有以下查询 returns 所有没有关联“-829”值的诊断。查询确实有效,但我认为我已经让它变得比应该的更难了。有更简洁的方法吗?

select distinct
c2.diagnosisn DiagnosisName, 
a2.text CareLookup
from core_patdiagnosis c1 
LEFT OUTER JOIN core_diagnosis c2 ON c1.diagnosis = c2.id 
LEFT OUTER JOIN core_carecontext c3 ON c1.carecontex = c3.id 
LEFT OUTER JOIN applookup_instance a1 ON c1.lkp_specialty = a1.id 
LEFT OUTER JOIN core_diagnosis_taxonomyma c5 ON c2.id = c5.id 
LEFT OUTER JOIN applookup_instance a3 ON c5.lkp_taxonomyna = a3.id 
LEFT OUTER JOIN applookup_instance a2 ON c3.lkp_context = a2.id

where c2.id IN
(
select c11.id core_diagnosis_c1_id
from core_diagnosis c11 
LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id 
LEFT OUTER JOIN applookup_instance a11 ON c21.lkp_taxonomyna = a11.id
WHERE
c11.isactive = 1
and a11.id != -829 or a11.id is null
)

AND
c2.id NOT IN
(
select c12.id ProcID
from core_procedure c12
LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id 
LEFT OUTER JOIN applookup_instance a12 ON c22.lkp_taxonomyna = a12.id
WHERE
c12.isactive = 1
and a12.id = -829 or a12.id is null
)

AND
c1.sys_creation_datetime > '01 Dec 2017 00:00:00' AND a2.text like 
'%Emergency%'

您可以使用 CTE(常用 Table 表达式 - see msdn page):

WITH BufferTableCTE (id) AS (...) SELECT ... FROM ... WHERE id in (SELECT id FROM BufferTableCTE WHERE id != -829) AND NOT id in (SELECT id FROM BufferTableCTE WHERE id = -829) AND ...

另一种方法是将中间结果存储在临时 table 中,然后稍后使用此临时 table(两次,一次使用 id != -829,一次使用 id = 829 )

这两种方式都会减少您重复的 sql 声明。

没有使用额外的东西

a2.text 如“%Emergency%”破坏了外部连接

select distinct c2.diagnosisn DiagnosisName, a2.text CareLookup
from core_patdiagnosis  c1 
JOIN core_diagnosis     c2 ON c2.id = c1.diagnosis  
JOIN core_carecontext   c3 ON c3.id = c1.carecontex 
JOIN applookup_instance a2 ON a2.id = c3.lkp_context     

where c2.id IN
( select c11.id 
  from core_diagnosis c11 
  LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id 
  LEFT OUTER JOIN applookup_instance a11        ON c21.lkp_taxonomyna = a11.id
  WHERE c11.isactive = 1 and a11.id != -829 
     or a11.id is null
)

AND
c2.id NOT IN
( select c12.id 
  from core_procedure c12
  LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id 
  LEFT OUTER JOIN applookup_instance a12        ON c22.lkp_taxonomyna = a12.id
  WHERE c12.isactive = 1 and a12.id = -829 
     or a12.id is null
)

AND c1.sys_creation_datetime > '01 Dec 2017 00:00:00' 

AND a2.text like '%Emergency%'