mysql多表更新的问题

MKD 2009-08-27 09:02:38
a表
supplier sum
1
2
3
4

b表
supplier_id amount month
1 100 2
2 15 3
2 16 8
3 20 9
1 30 4

能否不用循环的方法,根据supplier=supplier_id的关联,把统计的数据赋给a表的sum字段
也就是一句sql语句可以实现不?
update a,b set sum=sum+(select sum(amount) from b where supplier=supplier_id) where supplier_id=supplier;
这样没问题,可是如果
update a,b set sum=sum+(select sum(amount) from b where supplier=supplier_id and month<3) where supplier_id=supplier;
这样会出错,显示data truncated for column 'sum' at row..这样?
我怀疑可能部分sum(amount)得到的值为null引起的,该怎么解决
...全文
64 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
MKD 2009-08-27
  • 打赏
  • 举报
回复
成了,是ifnull(sum(amount),0),
感谢bdmh
MKD 2009-08-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bdmh 的回复:]
那就判断是否为空,为空就设置为0
accsess和sql server 都有判断函数
[/Quote]
怎么判断,试过isnull(sum(amount),0)通不过

[Quote=引用 2 楼 xzl_kye 的回复:]
update a
set a.sum1=c.s
from a ,(select supplier_id,SUM(amount) as s from b group by supplier_id) c
where a.supplier=c.supplier_id
[/Quote]
c是什么,sql语句通不过


我使用的数据库是mysql
xzl_kye 2009-08-27
  • 打赏
  • 举报
回复
update a
set a.sum1=c.s
from a ,(select supplier_id,SUM(amount) as s from b group by supplier_id) c
where a.supplier=c.supplier_id
bdmh 2009-08-27
  • 打赏
  • 举报
回复
那就判断是否为空,为空就设置为0
accsess和sql server 都有判断函数

2,495

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 数据库相关
社区管理员
  • 数据库相关社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧