mysql连接两个表,count和sum别名

时间:2014-07-15 20:15:34

标签: php mysql

我有查询

SELECT p. * , COUNT( r.poll_option_id ) AS voteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id ) 
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30

它返回我正确的数据

 id poll_id caption voteCount   
 1  1   32  1
 2  1   256 1
 3  1   512 0

现在我需要计算别名voteCount,所以对于这个例子,它将是1 + 1 + 0 = 2 ..并将其作为另一个别名返回。我怎么能这样做?我必须只使用1个查询,而且我没有编辑数据库的权限。我试过一些例子 MySQL Join two tables count and sum from second table MySQL query, COUNT and SUM with two joined tables 还有更多 但没有运气..

3 个答案:

答案 0 :(得分:1)

围绕它换行另一个查询?

SELECT id, poll_id, SUM(voteCount) AS votecount
FROM ( ... your query here ... ) As subquery
GROUP BY poll_id

答案 1 :(得分:1)

您可以通过计数列的计算总和

使用交叉联接到同一查询
SELECT t1.*,t2.totalvoteCount FROM (
SELECT p. * , COUNT( r.poll_option_id ) AS voteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id ) 
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30
) t1
CROSS JOIN (
SELECT SUM(voteCount) totalvoteCount
FROM (
SELECT  p.id,COUNT( r.poll_option_id ) AS voteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id ) 
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30
) t
) t2

输出如下

id poll_id caption voteCount   totalvoteCount 
 1  1       32          1        2
 2  1       256         1        2
 3  1       512         0        2

答案 2 :(得分:1)

在您的示例中,voteCount表示每个组的计数。如果您希望所有组中的计数,那么您可以省略group by子句(如果您的选择仅由count组成,那么这是合法的。)

SELECT COUNT(r.poll_option_id)
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON (r.poll_option_id = p.id)
WHERE p.poll_id =1

或者

SELECT p. * , COUNT( r.poll_option_id ) AS voteCount,
    (SELECT COUNT(r.poll_option_id)
    FROM poll_options AS p
    LEFT JOIN poll_responses AS r ON (r.poll_option_id = p.id)
    WHERE p.poll_id =1) totalVoteCount
FROM poll_options AS p
LEFT JOIN poll_responses AS r ON ( r.poll_option_id = p.id ) 
WHERE p.poll_id =1
GROUP BY p.id
LIMIT 0 , 30