在WHERE子句中使用别名时SQL中出错

时间:2016-03-09 05:25:24

标签: mysql sql

有3个表

doctor(doc_name.doc_id.dept_code,consult_fee)
dept(dept_name,dept_code)
patient(consult_fee,patient-name,doc_id)

查询显示所有医生的详细信息,其咨询次数少于“妇科”部门的所有医生。

我正在撰写查询

select count(b.consult_id) as top 
from info_faculty.wc_doctor a join info_faculty.wc_patient b on a.doc_id=b.doc_id 
where top <any (select count(b.consult_id) 
                 from info_faculty.wc_patient group by a.doc_id ) 
group by a.doc_id;

但它给了我错误

  

错误---“TOP”:标识符无效

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

select count(b.consult_id) as top 
from info_faculty.wc_doctor a join info_faculty.wc_patient b on a.doc_id=b.doc_id 
where count(b.consult_id) <any (select count(b.consult_id) 
                 from info_faculty.wc_patient group by a.doc_id ) 
group by a.doc_id;

我不知道任何来自哪里,但你不能在你的WHERE条款中使用你所做的别名。

答案 1 :(得分:0)

我相信这会奏效。请注意,您不在患者的字段列表中包含consult_id。

SELECT  a.doc_id, a.doc_name, a.dept_code, a.consult_fee, count(c.consult_id) 
FROM    test.doctor a,
        test.dept b,
        test.patient c
WHERE   a.doc_id = c.doc_id
AND a.dept_code = b.dept_code
AND b.dept_name != 'Gynaecology' #assuming you want to exclude doctors in Gynaecology dept
group by a.doc_id, a.doc_name, a.dept_code, a.consult_fee
Having count(c.consult_id) <   (SELECT count(b.consult_id) 
                    FROM test.dept a, test.patient b, test.doctor c 
                    WHERE a.dept_name = 'Gynaecology'
                    AND a.dept_code = c.dept_code 
                    AND c.doc_id = b.doc_id)