2017-03-14 47 views
0

我在Postgres上工作,下面的查詢似乎永遠不會執行,但它只是最終的OR導致問題,它運行良好,如果我註釋掉它。這僅僅是一種低效的寫作方式嗎?如果是這樣,我想不出一個替代方案。SQL Multiple OR BETWEENS

SELECT a.subject_id, a.hadm_id, a.admittime, d.icd9_code, l.short_title, d.seq_num 
FROM mimiciii.admissions a 
INNER JOIN mimiciii.diagnoses_icd d 
ON a.subject_id = d.subject_id 
AND a.hadm_id = d.hadm_id 
INNER JOIN mimiciii.d_icd_diagnoses l 
ON d.icd9_code = l.icd9_code 
WHERE a.subject_id IN 
    (SELECT DISTINCT d.subject_id 
    FROM mimiciii.diagnoses_icd d 
    WHERE d.icd9_code BETWEEN '390%' and '459%') 
    AND d.icd9_code NOT IN 
    (SELECT d.icd9_code 
     FROM mimiciii.diagnoses_icd d 
     WHERE d.icd9_code BETWEEN 'V01%' AND 'V91%' 
     OR d.icd9_code BETWEEN 'E000%' AND 'E999%' 
     OR d.icd9_code BETWEEN '630%' AND '679%' 
     OR d.icd9_code BETWEEN '760%' AND '999%' 
     ) 
ORDER BY subject_id, admittime 

回答

0

爲什麼需要子查詢?

不會返回你想要的東西嗎?

SELECT a.subject_id, a.hadm_id, a.admittime, d.icd9_code, l.short_title,  d.seq_num 
FROM mimiciii.admissions a 
INNER JOIN mimiciii.diagnoses_icd d 
ON a.subject_id = d.subject_id 
AND a.hadm_id = d.hadm_id 
INNER JOIN mimiciii.d_icd_diagnoses l 
ON d.icd9_code = l.icd9_code 

WHERE d.icd9_code BETWEEN '390%' and '459%' 
and not (d.icd9_code BETWEEN 'V01%' AND 'V91%') 
and not (d.icd9_code BETWEEN 'E000%' AND 'E999%') 
and not (d.icd9_code BETWEEN '630%' AND '679%') 
and not (d.icd9_code BETWEEN '760%' AND '999%')  
ORDER BY subject_id, admittime 

還是我誤會了某處?

2

也許一個原因,它從來沒有執行完畢,因爲BETWEEN s濾波所有行了。您不能使用通配符BETWEEN

整個子查詢看起來沒有必要。你可以刪除它。試試這個where條款:

WHERE a.subject_id IN (SELECT d.subject_id 
         FROM mimiciii.diagnoses_icd d 
         WHERE d.icd9_code >= '390' and 
          d.icd9_code < '460' 
        ) 

如果代碼匹配這一點,那麼它不符合你的其他條件。

我懷疑查詢還有其他問題,但這個問題很明顯。

+0

謝謝,但通配符正在工作。 – Sam

+0

@Sam。 。 。他們沒有做你認爲他們在做的事情。他們不是通配符;他們只是'%',這對任何閱讀查詢的人(包括將來的你)都會產生誤導。 –

0
SELECT a.subject_id, a.hadm_id, a.admittime, d.icd9_code, l.short_title, d.seq_num 
FROM mimiciii.admissions a 
INNER JOIN mimiciii.diagnoses_icd d 
ON a.subject_id = d.subject_id 
AND a.hadm_id = d.hadm_id 
INNER JOIN mimiciii.d_icd_diagnoses l 
ON d.icd9_code = l.icd9_code 
WHERE a.subject_id IN 
    (SELECT DISTINCT d.subject_id 
    FROM mimiciii.diagnoses_icd d 
    WHERE d.icd9_code BETWEEN '390%' and '459%') 
    AND d.icd9_code NOT IN 
    (SELECT d.icd9_code 
     FROM mimiciii.diagnoses_icd d 
     WHERE (d.icd9_code BETWEEN 'V01%' AND 'V91%') 
     OR (d.icd9_code BETWEEN 'E000%' AND 'E999%') 
     OR (d.icd9_code BETWEEN '630%' AND '679%') 
     OR (d.icd9_code BETWEEN '760%' AND '999%') 
     ) 
ORDER BY subject_id, admittime 

你可以嘗試(沒有測試過)使用括號命令在這種情況下,子查詢,會先評估括號然後運行或語句來收集數據反饋到外部查詢。

+0

謝謝你,把括號括起來帶來了錯誤的結果,但上面的評論確實有效。 – Sam