SQL子查询表达式

时间:2014-03-15 17:11:29

标签: sql subquery

SELECT  
    list_diagnosis_seq, list_diagnosis_icd10, 
    list_diagnosis_disease, list_diagnosis_diagtype
FROM    
    cmu_list_diagnosis, cmu_treatment
WHERE   
    (cmu_list_diagnosis.list_diagnosis_date = (SELECT MAX(list_diagnosis_date)  
                                               FROM cmu_list_diagnosis))
    AND cmu_list_diagnosis.treatment_id = (SELECT cmu_list_diagnosis.treatment_id
                                           FROM cmu_list_diagnosis, cmu_treatment 
                                           WHERE cmu_treatment.treatment_date = current_date
                                             AND cmu_treatment.patient_id = (SELECT cmu_patient.patient_id
                                                                             FROM cmu_patient, cmu_treatment
                                                                             WHERE cmu_patient.patient_id = cmu_treatment.patient_id));

我认为这是错误的

如何使这段代码正确?

谢谢大家:)

2 个答案:

答案 0 :(得分:0)

  

AND cmu_list_diagnosis.treatment_id =(SELECT   cmu_list_diagnosis.treatment_id                                                   来自cmu_list_diagnosis,cmu_treatment                                                   在哪里cmu_treatment.treatment_date = current_date AND   cmu_treatment.patient_id =(SELECT cmu_patient.patient_id

在上面的选择参考中,使用Top 1 或使用IN(选择......而不是#34; =选择"

答案 1 :(得分:0)

在不知道您的具体错误或您的DBMS的情况下,这个翻译可能有所帮助:

SELECT ListDiagnosis.list_diagnosis_seq
    ,ListDiagnosis.list_diagnosis_icd10
    ,ListDiagnosis.list_diagnosis_disease
    ,ListDiagnosis.list_diagnosis_diagtype
FROM cmu_list_diagnosis AS ListDiagnosis
INNER JOIN cmu_treatment AS Treatment ON Treatment.treatment_id = ListDiagnosis.treatment_id
    AND Treatment.treatment_date = CURRENT_DATE
INNER JOIN cmu_patient AS Patient ON Patient.patient_id = Treatment.patient_id
WHERE ListDiagnosis.list_diagnosis_date = (
    SELECT MAX(list_diagnosis_date) AS MaxDate
    FROM cmu_list_diagnosis
);

这会将您的语法转换为ANSI语法,从而消除了子查询的双重嵌套。 INNER JOIN应该提供您正在寻找的过滤,并且WHERE子句子查询中的日期别名应该消除某些DB(例如Teradata)将抛出的错误。