获取错误"操作数应包含1列"在这个查询上

时间:2015-11-04 19:06:59

标签: mysql sql

所以我有以下代码:

SELECT student_name FROM student S WHERE S.student_id IN
(SELECT t1.student_id, SUM(IF(t2.test_date IS NULL, 0, 1)) AS increase_score
FROM
test t1
LEFT JOIN test t2 
     ON t1.student_id = t2.student_id
     AND t1.test_date < t2.test_date
     AND t1.Score <= t2.Score
GROUP BY t1.student_id
HAVING 
     increase_score = 0
AND count(*) > 1)

我收到错误&#34;操作数应包含1列&#34;。这仅在添加外部SELECT语句后出现。我已经确认内部查询正在按预期工作。我已经查看了涉及相同错误的其他一些示例,但在这种情况下我无法确定如何解决此问题。

2 个答案:

答案 0 :(得分:1)

错误非常明确:您的子查询中不能有多个字段,显然您正在针对单个列对字段进行制作。 所以只需移动SUM子句中的HAVING

SELECT student_name
FROM student S
WHERE S.student_id IN
(SELECT t1.student_id
FROM test t1
LEFT JOIN test t2 
     ON t1.Name = t2.Name
     AND t1.Date < t2.Date
     AND t1.Score <= t2.Score
GROUP BY t1.Name
HAVING 
     SUM(IF(t2.test_date IS NULL, 0, 1)) = 0
AND count(*) > 1)

http://dev.mysql.com/doc/refman/5.7/en/any-in-some-subqueries.html

答案 1 :(得分:0)

用作in运算符的参数的查询必须返回单个列。重写此查询的一种方法是删除选择列表中的sum,并将其仅保留在having子句中:

SELECT student_name 
FROM   student 
WHERE  student_id IN (SELECT    t1.student_id
                      FROM      test t1
                      LEFT JOIN test t2 ON t1.Name = t2.Name AND 
                                           t1.Date < t2.Date AND
                                           t1.Score <= t2.Score
                      GROUP BY  t1.Name
                      HAVING    SUM(IF(t2.test_date IS NULL, 0, 1)) = 0 AND 
                                COUNT(*) > 1
                     )