我有这样的事情:
SELECT id, fruit, pip
FROM plant
WHERE COUNT(*) = 2;
我猜这个奇怪的查询是不言自明的。COUNT(*)
这里的意思是表中的行数plant
。我的要求是,仅当表中的总行数 = 2 时,我才需要从指定字段中检索值。这不起作用,但是:invalid use of aggregate function COUNT
。
我不能做到这一点:
SELECT COUNT(*) as cnt, id, fruit, pip
FROM plant
WHERE cnt = 2;
一方面,它将输出的行数限制为 1,另一方面,它给出了相同的错误:invalid use of aggregate function
.
我能做的是:
SELECT id, fruit, pip
FROM plant
WHERE (
SELECT COUNT(*)
FROM plant
) = 2;
但随后该子查询是重新运行的主要查询。我在这里展示了问题的较大部分的一个小示例,尽管我知道COUNT(*)
给定示例中的附加子查询并不是那么大的开销。
编辑:我不知道为什么这个问题被否决了。COUNT(*)
我试图从查询中的一个视图(一个临时表)中获取,这是一个具有 5 到 6 个连接和附加 where 子句的大型查询。将查询作为子查询重新运行以获取计数效率低下,我也可以看到瓶颈。
这是实际的查询:
SELECT U.UserName, E.Title, AE.Mode, AE.AttemptNo,
IF(AE.Completed = 1, 'Completed', 'Incomplete'),
(
SELECT COUNT(DISTINCT(FK_QId))
FROM attempt_question AS AQ
WHERE FK_ExcAttemptId = @excAttemptId
) AS Inst_Count,
(
SELECT COUNT(DISTINCT(AQ.FK_QId))
FROM attempt_question AS AQ
JOIN `question` AS Q
ON Q.PK_Id = AQ.FK_QId
LEFT JOIN actions AS A
ON A.FK_QId = AQ.FK_QId
WHERE AQ.FK_ExcAttemptId = @excAttemptId
AND (
Q.Type = @descQtn
OR Q.Type = @actQtn
AND A.type = 'CTVI.NotImplemented'
AND A.IsDelete = @status
AND (
SELECT COUNT(*)
FROM actions
WHERE FK_QId = A.FK_QId
AND type != 'CTVI.NotImplemented'
AND IsDelete = @status
) = 0
)
) AS NotEvalInst_Count,
(
SELECT COUNT(DISTINCT(FK_QId))
FROM attempt_question AS AQ
WHERE FK_ExcAttemptId = @excAttemptId
AND Mark = @mark
) AS CorrectAns_Count,
E.AllottedTime, AE.TimeTaken
FROM attempt_exercise AS AE
JOIN ctvi_exercise_tblexercise AS E
ON AE.FK_EId = E.PK_EId
JOIN ctvi_user_table AS U
ON AE.FK_UId = U.PK_Id
JOIN ctvi_grade AS G
ON AE.FK_GId = G.PK_GId
WHERE AE.PK_Id = @excAttemptId
-- AND COUNT(AE.*) = @number --the portion in contention.
请忽略上述查询,并从我发布的小示例查询中引导我走向正确的方向,谢谢。