如何将 sum(field_name) 存储在 MySql Select 语句中的变

How to store sum(field_name) in a variable within MySql Select statement?(如何将 sum(field_name) 存储在 MySql Select 语句中的变量中?)
本文介绍了如何将 sum(field_name) 存储在 MySql Select 语句中的变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将特定字段的总和存储在 MySQL Select 语句中的 @data := sum(field_name) 之类的变量中.

I am trying to store the sum total of a particular field in a variable like @data := sum(field_name) within MySQL Select statement.

以下是我的查询的确切示例:

Below is an exact example of my query:

SELECT a.id, @data1:=sum(b.amount) amount, @data1 as returned_val
FROM tbl_table1 a 
LEFT JOIN tbl_table2 b ON b.acount_id=a.id
GROUP BY a.id

请注意,我将 sum(b.amount) 存储到变量 @data1 并尝试将其显示在另一行中,但从未像我期望的那样工作.

Notice that I store the sum(b.amount) to a variable @data1 and tried to display it in another row but never work as what I'm expecting.

有没有其他方法可以做到这一点?

Is there any other way doing this?

推荐答案

不要在带有 GROUP BY 子句的 SELECT 语句中使用变量.

Do not use variables in SELECT statement with GROUP BY clause.

来自文档:

注意:在 SELECT 语句中,每个表达式仅在发送给客户.这意味着在 HAVING、GROUP BY 或 ORDER BY 中子句,您不能引用涉及变量的表达式在 SELECT 列表中设置.

Note: In a SELECT statement, each expression is evaluated only when sent to the client. This means that in a HAVING, GROUP BY, or ORDER BY clause, you cannot refer to an expression that involves variables that are set in the SELECT list.

使用子查询来实现-

SELECT t.id, @data1:=t.amount, @data1 AS returned_val FROM (
    SELECT a.id, SUM(b.amount) amount
    FROM tbl_table1 a 
    LEFT JOIN tbl_table2 b ON b.acount_id=a.id
    GROUP BY a.id
  ) t

这篇关于如何将 sum(field_name) 存储在 MySql Select 语句中的变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)