简体   繁体   中英

select rows and a sum from a single mysql table in one query

Recently, I'm trying to decrease the number of queries by joining unnecessary ones.

in this very case I came to a query that I should have used two queries : one to get the sum of all options and the other is the rows of the same table

SELECT `id`, `text`,`count`, SUM(`count`) AS sumoption
    FROM _options 

But when I'm trying to run this query , the result will be only one row , and I think its because I added SUM(count) . I know i should use group by to solve this issue but the table schema is not that simple .

id  text                  count
 1  Honda                   1        
 2  Benz                    0        
 3  Toyota                  1  

now the sum should be 2 and the it should list all options and their values.
How can I make this happen ?


PS. : The expected outcome :

 Honda                   1        
 Benz                    0        
 Toyota                  1  
 Sum of counts : 2 

Something like this looks more logical:

SELECT m.id, m.name, count(o.man_id) AS sumoption
FROM _options o 
RIGHT JOIN manufacturers m ON (m.id = o.man_id)
GROUP BY m.id WITH ROLLUP

In your case you can also use:

SELECT id, `text`, SUM(`count`) AS sumoption
FROM _options 
GROUP BY id WITH ROLLUP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM