2

我正在尝试运行一个查询,该查询返回在名为 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)

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

4

3 回答 3

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;
于 2013-02-24T02:41:29.030 回答
2
SELECT doctorID
FROM Hospital 
WHERE doctorID IN

(SELECT temp.doctorID 
FROM Hospital as temp
GROUP BY temp.doctorID
HAVING count(temp.doctorID)>3);
于 2013-02-24T02:42:19.483 回答
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);
于 2013-02-24T02:41:24.027 回答