[英]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) . 但是,当我尝试运行此查询时,结果将只有一行,并且我认为是因为我添加了SUM(count)。 I know i should use group by to solve this issue but the table schema is not that simple .
我知道我应该使用group by解决此问题,但是表架构并不是那么简单。
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. 现在总和应为2,并且应列出所有选项及其值。
How can I make this happen ? 我怎样才能做到这一点?
PS. 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.