简体   繁体   English

在一个查询中从单个mysql表中选择行和总和

[英]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.

相关问题 Mysql查询选择其中一个表中的总和与另一个表中的行总和进行比较 - Mysql Query select where the sum from one table is compared to the sum of rows in another table MySQL - Select 一次查询中来自不同表的多行 - MySQL - Select multiple rows from different table in one query Mysql-将sum作为单个表中一个字段中的行之一输出 - Mysql - output of sum as one of the rows in one field in a single table MYSQL单一查询可从一个表中检索单行,也可从另一表中检索多个行作为单个字段 - MYSQL Single query to retrieve both single row from one table and many rows as a single field from another MySQL:如何从一个表中选择和显示所有行,并计算另一个表中where子句的总和? - MySQL: How to select and display ALL rows from one table, and calculate the sum of a where clause on another table? 如何在mysql的单个列中对多个选择查询求和? - How sum the more than one select query in a single column in mysql? mysql join查询从两个表中选择行,一个表有多个与第一个表匹配的行 - mysql join query for select rows from two tables that one table is having multiple rows matching to the first table MySQL SUBTRACT,使用SUM查询同一列的单表 - MySQL SUBTRACT with SUM Query for One Single Column Same Table MySQL查询-一个表中的单行,另一表中的多行 - MySQL query - single row in one table with multiple rows in another table MySQL项目设计-根据另一个选择查询中的行有条件地从一个表中选择 - MySQL project design - conditionally select from one table based on rows from another select query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM