简体   繁体   English

MySQL 在选择查询中使用生成的列

[英]MySQL use generated column in select query

I have a MySQL query that runs a brief operation (totalling the counts in a select statement) and I want to use the result to do a math operation, but I'm getting an error.我有一个运行简短操作的 MySQL 查询(汇总 select 语句中的计数),我想使用结果进行数学运算,但出现错误。

Table:桌子:

id  |   group   |   count   |
-----------------------------
1       1           3
2       1           2

Query:询问:

select id, count,
  (select sum(count) from table group by group) as total,
  count/total as percent 
from table

The error is because there is no real "total" column in the table.错误是因为表中没有真正的“总计”列。 How can I make the query work?我怎样才能使查询工作?

You can save total as a variable , then use that in the division calculation.您可以将total保存为变量,然后在除法计算中使用它。

SELECT 
  `id`, `count`, 
   @total:=(SELECT sum(`count`) FROM `table` GROUP BY `group`) AS `total`, 
  `count`/@total AS `percent` 
FROM `table`

NOTE: GROUP is a reserved word in MySQL.注意: GROUP是 MySQL 中的保留字 You should enclose it (and all other field/table names) in backticks (`).应该将它(以及所有其他字段/表名称)括在反引号 (`) 中。

You can also do this without introducing a variable:您也可以在不引入变量的情况下执行此操作:

select id, 
   count, 
   (select sum(count) from `table` group by `group`) as total, 
   (select count/total) as percent 
from `table`;

Produces:产生:

+------+-------+-------+---------+
| id   | count | total | percent |
+------+-------+-------+---------+
|    1 |     3 |     5 |  0.6000 |
|    2 |     2 |     5 |  0.4000 |
+------+-------+-------+---------+
2 rows in set (0.05 sec)

Your problem is that the inner query needs to generate 1 result per row, not 1 for every group.您的问题是内部查询需要为每行生成 1 个结果,而不是每个组生成 1 个结果。 You want to add a where clause in the inner query saying something like您想在内部查询中添加一个 where 子句,例如

where inner_table.group = outer_table.group

so that only one result is returned.这样只返回一个结果。

This question already has an answer for MySql but by mistake if anyone lands here for MSSql as i did, it is as simple as below for MSSql这个问题已经有了 MySql 的答案,但是如果有人像我一样在这里登陆 MSSql,那么对于 MSSql 来说就像下面一样简单

select id, count,
  total = (select sum(count) from table group by group),
  count/total as percent 
from table

group is a reserved word in mysql, as is table , you should use it like: group是 mysql 中的保留字,就像table ,您应该像这样使用它:

select id, count, (select sum(count) from `table` group by `group`) as total, count/total as percent from `table`

For more information: MySQL Reserved Words有关更多信息: MySQL 保留字

You'll see there that you can actually use count but I would put all table and column names in quotes anyway.您会在那里看到实际上可以使用count但无论如何我都会将所有表和列名称放在引号中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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