数据库中的多个Count()

时间:2012-05-07 00:45:40

标签: mysql

我正在使用winforms和VB进行调查。这是我到目前为止显示统计信息的SQL:

SELECT
    tblAlt.altText,
    Count(tblAnswers.answerID)
FROM tblAlt
LEFT JOIN tblAnswers ON (tblAlt.altId = tblAnswers.altID)
WHERE tblAlt.questionID = " & CInt(questionID) & "
GROUP BY tblAlt.altText;

这会返回问题的每个备选方案,以及有多少人回答它们。有没有一种方法可以计算使用相同的SQL查询总共回答了多少?

涉及的表格是:

_______________     _______________     ___________  _______________
|_tblUsers____|     |_tblAnswers___|    |_tblAlt__|  |_tblQuestion_|
| userID      |     | answerAltID  |    | altID   |  | questID     |
| username    |     | userID       |    | altText |  | questText   |
|_____________|     |______________|    |_questID_|  |_____________|

任何帮助将不胜感激!

这是我最后使用的:

SELECT
tblAlt.altText,
Count(tblAnswers.answerID),
(SELECT COUNT(answerID) FROM tblAnswers, tblAlt 
WHERE tblAnswers.answerAltID = tblAlt.altID 
AND tblAlt.questID = " & CInt(questionID) & ") as total_count
FROM tblAlt
LEFT JOIN tblAnswers ON (tblAlt.altId = tblAnswers.altID)
WHERE tblAlt.questID = " & CInt(questionID) & "
GROUP BY tblAlt.altText;

2 个答案:

答案 0 :(得分:2)

使用ROLLUP:

SELECT
    tblAlt.altText,
    Count(tblAnswers.answerID)
FROM tblAlt
LEFT JOIN tblAnswers ON (tblAlt.altId = tblAnswers.altID)
WHERE tblAlt.questionID = " & CInt(questionID) & "
GROUP BY tblAlt.altText WITH ROLLUP;

如果您想要一次性计算(以提高查询效率),请使用CROSS JOIN。别担心,这个CROSS JOIN不会产生笛卡尔积,它只有一排。这可能比子查询方法更快:

SELECT
tblAlt.altText,
Count(tblAnswers.answerID), x.total_count    
FROM tblAlt
cross join (SELECT COUNT(answerID) as total_count FROM tblAnswers) as x 

LEFT JOIN tblAnswers ON (tblAlt.altId = tblAnswers.altID)
WHERE tblAlt.questionID = " & CInt(questionID) & "
GROUP BY tblAlt.altText;

或者使用MySqlism,可能会更快:

SELECT
tblAlt.altText,
Count(tblAnswers.answerID), @total_count as total_count
FROM tblAlt
cross join (SELECT @total_count := COUNT(answerID) FROM tblAnswers) as x

LEFT JOIN tblAnswers ON (tblAlt.altId = tblAnswers.altID)
WHERE tblAlt.questionID = " & CInt(questionID) & "
GROUP BY tblAlt.altText;

或者您可以使用多语句。注意,SET语句不会出现在ADO.NET的DataReader或DataTable上。 ADO.NET仍然可以从您的实际查询中获得结果。在所有方法中,这一点肯定更快:

SET @total_count := (SELECT COUNT(answerID) FROM tblAnswers);
SELECT
tblAlt.altText,
Count(tblAnswers.answerID), @total_count as total_count
FROM tblAlt
LEFT JOIN tblAnswers ON (tblAlt.altId = tblAnswers.altID)
WHERE tblAlt.questionID = " & CInt(questionID) & "
GROUP BY tblAlt.altText;

答案 1 :(得分:1)

您可以使用子查询来执行此操作,例如:

SELECT
tblAlt.altText,
Count(tblAnswers.answerID),
(SELECT COUNT(answerID) FROM tblAnswers) as total_count
FROM tblAlt
LEFT JOIN tblAnswers ON (tblAlt.altId = tblAnswers.altID)
WHERE tblAlt.questionID = " & CInt(questionID) & "
GROUP BY tblAlt.altText;

一些资源:

http://beginner-sql-tutorial.com/sql-subquery.htm

http://www.1keydata.com/sql/sql-subquery.html