select sum(bales) as bales
from receive_bardana
join receive_wheat
on receive_bardana.id = receive_wheat.id
where id=1
我的结果显示错误的输出
答案 0 :(得分:0)
您的查询1)甚至在where子句中给定id的语法都不应该包含歧义2)联接表是没有意义的,因为您在select中没有使用它的任何内容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)
充分解释了您遇到的“问题”。 如果您想对自己想做的事情给出答案,我建议您提出一个新问题来描述自己要做的事情,而不是仅仅说这段代码并不能达到我的期望(实际上,它可以实现我所期望的并且是不是“错”)