MySQL:表别名不起作用

时间:2015-09-01 11:14:00

标签: mysql

我想重写此查询,以便它可以使用表和列别名,但我无法使其正常工作。经过一些研究后我发现我们不能在WHERE子句中使用表别名,我试图将WHERE更改为HAVING,但仍然没有工作......

有没有人有更好的主意?

这是查询:

SELECT   pos.pat_id+1000 as Barcode
        ,pat_sex as Sex 
        ,pat_dob as DoB
        ,Test 
        ,Required_diagnosis
        ,Sample_date
        ,Location 
        ,DQ_list

FROM    (SELECT  icv_pat_id as pat_id
            ,icv_test_name as Test
            ,'Trichomonas' as Required_diagnosis
            ,lrr_request_date as Sample_date
            ,d.Location
            ,d.DQ_List          
        FROM investigation_component_values
        INNER JOIN lab_result_records l on l.lrr_rrc_id = icv_rrc_id
        LEFT JOIN lookups.dq_lists d ON d.lrr_ordering_location_name = l.lrr_ordering_location_name
        WHERE lrr_request_date BETWEEN '2015-08-01' AND '2015-08-31'
        AND icv_pat_id NOT IN (SELECT pat_id FROM cnwlreports.test_patients)
        AND icv_ist_id = 83882
        AND icv_non_quantifiable_result = 'Trichomonas vaginalis ISOLATED') as pos
LEFT JOIN trungnguyen.patients pat on  pos.pat_id = pat.pat_id

WHERE pos.pat_id NOT IN (SELECT DISTINCT p.pat_id
                        FROM pos p
                        LEFT JOIN (SELECT    rrc_pat_id as pat_id
                                            ,rrc_clinic_date as diag_date                                               
                                    FROM referral_records 
                                    WHERE rrc_status = 'approved'
                                    AND rrc_answered_id = 17380
                                    AND rrc_clinic_date BETWEEN DATE_SUB('2015-08-01',INTERVAL 7 DAY) 
                                    AND DATE_ADD('2015-08-31',INTERVAL 7 DAY) 
                                    AND rrc_pat_id IN (SELECT pat_id FROM pos)
                                    GROUP BY    rrc_pat_id 
                                                ,rrc_clinic_Date) d ON p.pat_id = d.pat_id
                        WHERE ABS(datediff(sample_date,diag_date)) < 7
                        )
;

3 个答案:

答案 0 :(得分:1)

评论太长了。

您将表别名和列别名混淆。列别名在SELECT中定义,不能在WHERE的{​​{1}}子句中使用。

table 别名在SELECT子句中定义。只要使用该表中的列,就可以 - 而且应该 - 使用它。具有表别名的此类列名称为限定列

例如,来自子查询:

FROM

SELECT icv.icv_pat_id as pat_id, icv.icv_test_name as Test, 'Trichomonas' as Required_diagnosis, lrr.lrr_request_date as Sample_date . . . FROM investigation_component_values icv INNER JOIN lab_result_records lrr on lrr.lrr_rrc_id = icv.icv_rrc_id WHERE lrr.lrr_request_date BETWEEN '2015-08-01' AND '2015-08-31' . . . pat_idtestRequired_diagnosis都是列别名Sample_dateicv别名。在lrr子句中,您可以:

WHERE

但你不能拥有:

WHERE lrr.lrr_request_date BETWEEN '2015-08-01' AND '2015-08-31' . . .

答案 1 :(得分:0)

您可以使用真实的列名,因此在&#39; WHERE pos.pat_id&#39;例如,你应该使用:&#39; WHERE pos.icv_pat_id&#39;。

答案 2 :(得分:0)

通常你可以在where子句中使用table的别名; 通常,我这样做:

Select * from Table T, Table2 T2 WHERE T.key = T2.key;

例如,尝试使用此语法显式内连接。