【问题标题】:how to use sum function with join in MySQL如何在 MySQL 中使用 sum 函数和 join
【发布时间】:2019-07-17 05:47:21
【问题描述】:
select sum(bales) as bales 
  from receive_bardana  
  join receive_wheat
    on receive_bardana.id = receive_wheat.id 
 where id=1

我的结果显示错误的输出

【问题讨论】:

  • 请添加一些示例数据的表架构
  • 假设 bales 是一种数字数据类型,则查询应该可以工作,因此您需要通过提供表定义和样本数据来证明它不能工作,
  • 输出对我来说很好
  • 不加入其显示正确值但加入其显示增加值
  • 不,不是。无论哪种方式,它看起来都完全相同。

标签: mysql join sum


【解决方案1】:

您的查询 1) 甚至不应该在 where 子句中给定 id 的语法不明确 2) 连接表是没有意义的,因为您在选择中没有使用它的任何内容 3) 根据您在问题中提供的少量信息在 receive_bardana 和 receive_wheat 之间存在一对多的关系,这意味着总和是在所有连接的行上,例如

create table receive_bardana(id int,bales int);  
create table receive_wheat(id int);

insert into receive_bardana values (1,10),(2,20);  
insert into receive_wheat values(1),(1),(2),(2),(2);

select *
  from receive_bardana  
  join receive_wheat
    on receive_bardana.id = receive_wheat.id 
 where receive_bardana.id;

结果

+------+-------+------+
| id   | bales | id   |
+------+-------+------+
|    1 |    10 |    1 |
|    1 |    10 |    1 |
|    2 |    20 |    2 |
|    2 |    20 |    2 |
|    2 |    20 |    2 |
+------+-------+------+
5 rows in set (0.00 sec)

以及您的(固定)查询

select sum(bales) as bales 
  from receive_bardana  
  join receive_wheat
    on receive_bardana.id = receive_wheat.id 
 where receive_bardana.id;

总和正确返回

+-------+
| bales |
+-------+
|    80 |
+-------+
1 row in set (0.00 sec)

这完全解释了您遇到的“问题”。 如果您想知道您正在尝试做什么,我建议您提出一个新问题来描述您正在尝试做什么,而不是仅仅说这段代码没有按照我的预期执行(实际上它符合我的预期并且是没有'错')

【讨论】:

    猜你喜欢
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2021-06-18
    • 2014-07-27
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多