0

I have the below query that returns all diagnosis that do not have a '-829' value associated to them. The query does work but I think that I've made it harder than it should be. Is there a tidier way of doing this?

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%'
4

2 回答 2

0

多余的东西没用

a2.text like '%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%'
于 2018-01-08T14:02:48.300 回答
-1

您可以使用 CTE(公用表表达式 -请参阅 msdn 页面):

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 ...

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

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

于 2018-01-08T12:07:44.157 回答