子查询没有给出输出

时间:2013-02-24 02:39:19

标签: mysql sql subquery aggregate-functions

我正在尝试运行一个查询,该查询返回在名为Hospital的表中出现超过3次的ID列表。到目前为止,我已经想出了这个:

SELECT doctorID
FROM Hospital 
WHERE doctorID IN

(SELECT temp.doctorID, count(temp.doctorID) as frequency
FROM Hospital as temp
GROUP BY temp.doctorID
HAVING frequency >3);

但出于某种原因,我在运行时遇到错误

Code: 1241. Operand should contain 1 column(s)

当我环顾四周时似乎是一个流行的错误,但我找不到适用于我的现有解决方案。当我在括号中运行查询时,它可以正常工作。那么为什么它不能作为子查询工作呢?

3 个答案:

答案 0 :(得分:3)

从子查询中删除第二列,将count()移到HAVING子句中:

SELECT doctorID
FROM Hospital 
WHERE doctorID IN

(SELECT temp.doctorID
FROM Hospital AS temp
GROUP BY temp.doctorID
HAVING count(temp.doctorID) > 3);

如果没有子查询,您可以使结果更简单:

SELECT doctorID
FROM   Hospital
GROUP  BY doctorID
HAVING count(doctorID) > 3;

答案 1 :(得分:2)

SELECT doctorID
FROM Hospital 
WHERE doctorID IN

(SELECT temp.doctorID 
FROM Hospital as temp
GROUP BY temp.doctorID
HAVING count(temp.doctorID)>3);

答案 2 :(得分:1)

您的子查询返回2列。从SELECT列表中删除COUNT列,如下所示:

SELECT doctorID
FROM Hospital 
WHERE doctorID IN
   (SELECT temp.doctorID
   FROM Hospital as temp
   GROUP BY temp.doctorID
   HAVING count(temp.doctorID) >3);